Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope Elasticsearch Results to Specific Ids

I have a question about the Elasticsearch DSL.

I would like to do a full text search, but scope the searchable records to a specific array of database ids.

In SQL world, it would be the functional equivalent of WHERE id IN(1, 2, 3, 4).

I've been researching, but I find the Elasticsearch query DSL documentation a little cryptic and devoid of useful examples. Can anyone point me in the right direction?

like image 694
mindtonic Avatar asked Jan 20 '16 22:01

mindtonic


2 Answers

Here is an example query which might work for you. This assumes that the _all field is enabled on your index (which is the default). It will do a full text search across all the fields in your index. Additionally, with the added ids filter, the query will exclude any document whose id is not in the given array.

{
  "bool": {
    "must": {
      "match": {
        "_all": "your search text"
      }
    },
    "filter": {
      "ids": {
        "values": ["1","2","3","4"]
      }
    }
  }
}

Hope this helps!

like image 69
BrookeB Avatar answered Sep 28 '22 09:09

BrookeB


As discussed by Ali Beyad, ids field in the query can do that for you. Just to complement his answer, I am giving an working example. In case anyone in the future needs it.

GET index_name/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "field": "your query"
          }
        },
        {
          "ids" : {
            "values" : ["0aRM6ngBFlDmSSLpu_J4", "0qRM6ngBFlDmSSLpu_J4"]
          }
        }
      ]
    }
  }
}
like image 27
msayef Avatar answered Sep 28 '22 10:09

msayef