How to apply filter using NEST (.NET)

I am trying to query my server using the .NET library NEST (GitHub - elastic/elasticsearch-net: Elasticsearch.Net & NEST)

I want my query to find any data where source = "abc" and source_id in (" 123","145","158m")

I executed the following using using Postman and it worked

{
    "query": {
        "bool" : {
            "must": {
                "multi_match": {
                    "query": "abc",
                    "fields": [
                        "source"
                    ]
                }
            },
            "filter" : {
                "terms" : {
                    "source_id" : ["123","145","158m"]
                }
            }
        }        
    },
    "fields": ["source_id"],
    "_source": false
}

First, is there a better query (for performance) to get the same data?

Second, I can't find a way to apply the Filter part into the query using the .net library.

Here is my c# code

var mySourceIds = new [] { "123","145","158m" }
var documents = await elasticClient.SearchAsync<MyRecord>(s => 
   s.Query(q =>
       q.Bool(b =>
          b.Must(m =>
              m.MultiMatch(mm =>
                  mm.Query("abc")
                    .Fields(new Field("source"))
              )
        ).Filter(f => f.Terms(ft => ft.Field(ftf => mySourceIds.Contains(ftf.SourceId))))
     )
   ).Fields(new Field("source_id"))
   .Source(false)
);

However, the above code does not generate the filter part in the query

"filter" : {
                "terms" : {
                    "source_id" : ["123","145","158m"]
                }
            }

How can I set the terms in the filter using the .net library?

I figured it out

var mySourceIds = new [] { "123","145","158m" }
var documents = await elasticClient.SearchAsync<MyRecord>(s => 
   s.Query(q =>
       q.Bool(b =>
          b.Must(m =>
              m.MultiMatch(mm =>
                  mm.Query("abc")
                    .Fields(new Field("source"))
              )
        ).Filter(f => f.Terms(ft => ft.Field(new Field("source_id")).Terms(mySourceIds)))
     )
   ).Fields(new Field("source_id"))
   .Source(false)
);

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.