Search code examples
c#elasticsearchnest

ElasticSearch query using Nest - Match Field to one of a few options


I have an elastic index with a keyword "user_id" field. I would like to get all documents that are of a group of users.

{
...,
"user_id": "031aeda2-b552-4a16-9ae6-68a24492e252",
...,
}

I want to get documents that belong to one or more user_ids, i.e. - get documents that have user_id: "031aeda2-b552-4a16-9ae6-68a24492e252" or "031fffa2-c552-4a16-9ae6-68a24492e141" or ...

How can I do it on Nest?


Solution

  • Since standard analyzer provides grammar based tokenization, it will split your text on hypen , so use on keyword field

    Nest has two syntax

    Fluent and Object initializer

    Using fluent syntax above can be resolved using Terms query.

    _elasticClient                
     .Search<Users>(s => s
     .From(0).Size(10)
     .Query(q => q.Terms(p => p.Field(c => c.user_id.Suffix("keyword"))
                                            .Terms(new List<string> { "1" }))));
    
    

    *Replace Users with your model.

    If you need to dynamically create query, you can use object initializer syntax of NEST