Search code examples
elasticsearchelasticsearch-dslelasticsearch-rails

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?


Solution

  • 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!