vijayst
vijayst

Reputation: 21846

How do I search within an list of strings in Elastic Search?

My data has a field localities which is an array of strings.

"localities": [
"Mayur Vihar Phase 1",
"Paschim Vihar",
"Rohini",
"",
"Laxmi Nagar",
"Vasant Vihar",
"Dwarka",
"Karol Bagh",
"Inderlok"  ]

What query should I write to filter the documents by a specific locality such as "Rohini"?

Upvotes: 1

Views: 4645

Answers (2)

forzagreen
forzagreen

Reputation: 2683

POST /_search
{
  "query": {
    "match": {
      "localities": "Rohini"
    }
  }
}

Or you can simply query:

GET /_search?q=localities:Rohini

Upvotes: 0

ThomasC
ThomasC

Reputation: 8165

A simple match query will be enough (if you don't know the mapping of your localities field).

POST <your index>/_search
{
  "query": {
    "match": {
      "localities": "Rohini"
    }
  }
}

If the localities field is set as a string type and index as not_analyzed, the best way to query this is to use a term filter, wrapped in a filtered query (you can't use directly filters) :

POST <your index>/_search
{
  "query": {
    "filtered": {
      "filter": {
        "term": {
          "localities": "Rohini"
        }
      }
    }
  }
}

If you doesn't need the score, the second solution is the way to go as filters doesn't compute score, are faster and cached.

Check the documentation for information about analysis which is a very important subject in ElasticSearch, heavily influencing the way you query.

Upvotes: 1

Related Questions