Search code examples
elasticsearchelasticsearch-5elasticsearch-rails

How to query two different fields with different query terms in same request. ElasticSearch 5.x


new to ElasticSearch - start loving it. I am working on a Rails application (using elasticsearch-rails / elasticsearch-model).

I have two fields - both strings consisting of Tags.

about_me & about_you

  • Now I was to query the about_you of another user with the current users about_me.
  • At the same time, I wish to query the about_me of the other users with the about_you of the current user.

Does this make sense? Like two fields, two queries and each query is aimed at a particular field.

I just need a hint how this can be achieved in ES. For the sake of completeness, here is the part method I created in my rails model - it is incomplete:

def home_search(query_you, query_me)
  search_definition =
      {
          query: {
              multi_match: {
                  query: query_me,
                  fields: ['about_you']
              }
              ..... SOMETHINGs MISSING HERE ..... ?
          },
          suggest: {
              text: query,
              about_me: {
                  term: {
                      size: 1,
                      field: :about_me
                  }
              },
              about_you: {
                  term: {
                      size: 1,
                      field: :about_you
                  }
              }
          }
      }
  self.class.__elasticsearch__.search(search_definition)
end

Any help, link or donations are welcome. Thank you!


Solution

  • I'm not sure I've understood your question but I can suggest two options:
    First Use a bool query of type should and minimum_should_match=1. In this case you can write two queries for you'r searches. and If you want to distinguish between results you can pass a _name parameter in each query. something like this:

    {
       "query": {
          "bool": {
             "minimum_should_match": 1,
             "should": [
                {
                   "multi_match": {
                      "query": "query_me",
                      "fields": [
                         "about_you"
                      ],
                      "_name": "about_you"
                   }
                },
                {
                   "multi_match": {
                      "query": "query_you",
                      "fields": [
                         "about_me"
                      ],
                      "_name": "about_you"
                   }
                }
             ]
          }
       }
    }
    

    By providing _name you can see which queries are hitted in your search result. The second approach could be a _msearch query which in which you can pass multiple queries to the endpoint and get the results back. Here are some useful links:

    Bool Query
    Named Queries