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

Time:04-22

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]?

CodePudding user response:

You can use below Elasticsarch 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 stroing id in seperate 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))      
        )
);

CodePudding user response:

You can use the terms query to achieve your use-case, in JSON it would look like below.

GET /_search
{
  "query": {
    "terms": {
      "tbl.id": [ 1,2,4 ],
      "boost": 1.0
    }
  }
}
  • Related