'Elasticsearch multiple model query

I am setting Elastic Search on a Rails project.

I have followed this tutorial: https://medium.com/wolox/from-zero-to-hero-multimodel-autocompletion-search-with-elasticsearch-rails-3beff17fa8c6

I have Two models:

  • A(title, description)
  • B(name)

My query looks like this

    search_query = {
      "size": 50,
      "query": {
        "function_score": {
          "query": {
            "bool": {
              "should": [{
                "multi_match": {
                  "query": @text_query,
                  "fields": %w[title description name],
                  "fuzziness": 'auto'
                }
              }]
            }
          }
        }
      }
    }

Elasticsearch::Model.search(search_query, [A, B]).records

I get as a response an array of with result of types A and B

Actual => [A, A, B, A]

I would like to have a defined number of B results and A.

Wanted => {A : [A, A, A], B: [B]}

Is it possible with only one ES query ? Should I go with one query per model ?

Thank you for your help!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source