Search code examples
.netelasticsearch

How to form a query to find all records whose id is present in some list, for example [1, 3, 10]?


How to use .nest NEST in Elasticsearch to form a query like: select * from tbl where tbl.id in [1, 3, 10] ? Or in other words, how to form a query to find all records whose id is present in some list, for example [1, 3, 10]?


Solution

  • You can use below ElasticSearch query for searching on document _id field.

    POST index1/_search
    {
      "query": {
        "ids": {
          "values": ["1","2","3"]
        }
      }
    }
    

    Below is equivalent .Net code.

    var ids = new long[] { 1, 2, 3 };
    
    var multiGetResponse = client.Search<MyDocument>(s => s
        .Index("index1")
        .Query(q => q
            .Ids(i => i
                .Values(ids)
            )
        )
    );
    

    If you are storing id in separate field in ElasticSearch document then you can use below query:

    POST index1/_search
    {
      "query": {
        "terms": {
          "id": ["1","2","3"]
        }
      }
    }
    

    Below is equivalent .Net code.

    client.Search<MyDocument>(s => s
            .Index("index1")
            .Query(q => q      
                .Terms(t => t.Field(f => f.Name).Terms(ids))      
            )
    );