zhuber
zhuber

Reputation: 5524

Elastic Search NEST client raw + custom query

I'm using NEST client for querying ES, but now I have a specific situation - I'm trying to proxy query to ES, but with specific query applied by default:

public IEnumerable<TDocument> Search<TDocument>(string indexName, string query, string sort, int page, int pageSize) where TDocument : class
{
    var search = new SearchRequest(indexName)
    {
        From = page,
        Size = pageSize,
        Query = new RawQuery(query),
    };


    var response = this.client.Search<TDocument>(search);

    return response.Documents;
}

Code above is just proxying query to ES, but what if I need to apply specific filter that should be always applied along with passed query?

So for example I'd want Active field to be true by default. How can I merge this raw query with some specific and always applied filter (without merging strings to formulate merged ES API call if possible).

Upvotes: 0

Views: 759

Answers (1)

Russ Cam
Russ Cam

Reputation: 125498

Assuming that query is well formed JSON that corresponds to the query DSL, you could deserialize it into an instance of QueryContainer and combine it with other queries. For example

var client = new ElasticClient();

string query = @"{
  ""multi_match"": {
    ""query"": ""hello world"",
    ""fields"": [
      ""description^2.2"",
      ""myOtherField^0.3""
    ]
  }
}";

QueryContainer queryContainer = null;

using (var stream = client.ConnectionSettings.MemoryStreamFactory.Create(Encoding.UTF8.GetBytes(query)))
{
    queryContainer = client.RequestResponseSerializer.Deserialize<QueryContainer>(stream);
}

queryContainer = queryContainer && +new TermQuery
{
    Field = "another_field",
    Value = "term"
};

var searchResponse = client.Search<TDocument>(s => s.Query(q => queryContainer));

which will translate to the following query (assuming default index is _all)

POST http://localhost:9200/_all/_search?pretty=true&typed_keys=true 
{
  "query": {
    "bool": {
      "filter": [{
        "term": {
          "another_field": {
            "value": "term"
          }
        }
      }],
      "must": [{
        "multi_match": {
          "fields": ["description^2.2", "myOtherField^0.3"],
          "query": "hello world"
        }
      }]
    }
  }
}

Upvotes: 2

Related Questions