kgangadhar
kgangadhar

Reputation: 5088

Matching multiple fields with elastic search query string

I am new to elastic search, I have data in the following format:

{
  "person_name" : "Abraham Benjamin deVilliers",
  "name": "Abraham",
  "office":{
     "name":"my_office"
  }
},
{
  "person_name" : "John Bradshaw",
  "name": "john",
  "office": {
     "name":"Abraham deVilliers"
  }
},
{
  "person_name" : "John Bradshaw",
  "name": "Abraham deVilliers",
  "office": {
     "name":"blabla"
  }
},
{
  "person_name" : "John Bradshaw",
  "name": "Abraham",
  "office": {
     "name":"deVilliers"
  }
},
{
  "person_name" : "Abraham",
  "name": "deVilliers",
  "office": {
     "name":"blabla"
  }
}

I am working on search query to match a string with three fields person_name, name and office.name, which should return response by checking user entered query fields as follows:

If entered query string is Abraham deVilliers, then it should return users having both Abraham and deVilliers as part of their person_name or name or office.name as below:

   {
      "person_name" : "Abraham Benjamin deVilliers",
      "name": "Abraham",
      "office":{
         "name":"my_office"
      }
    },
    {
      "person_name" : "John Bradshaw",
      "name": "john",
      "office": {
         "name":"Abraham deVilliers"
      }
    },
    {
      "person_name" : "John Bradshaw",
      "name": "Abraham deVilliers",
      "office": {
         "name":"blabla"
      }
    }

I have tried with query_string search query of elastic search as follows:

{
    "query": {
        "query_string":
          {   "fields": ["person_name", "name", "office.name"],
              "query": "Abraham AND deVilliers"
          }
    }
}

The search query returns expected result but it also returns response matching first_name: Abraham from name and last_name: deVilliers from office.name, which i don't want.

I want to exclude below profiles from returning by the query_string query

    {
      "person_name" : "John Bradshaw",
      "name": "Abraham",
      "office": {
         "name":"deVilliers"
      }
    },
    {
      "person_name" : "Abraham",
      "name": "deVilliers",
      "office": {
         "name":"blabla"
      }
    }

Upvotes: 1

Views: 3031

Answers (1)

aclowkay
aclowkay

Reputation: 3897

This a job for multimatch query, try something like this:

GET <index_name>/_search?explain=true
{
  "query": {
    "multi_match" : {
      "query":      "Abraham deVilliers",
      "type":       "best_fields",
      "fields":     [ "person_name", "name", "office.name" ],
      "operator":"and"
    }
  }
}

Upvotes: 1

Related Questions