Is it possible to combine results for .DateRange and .QueryString using NEST client?

I currently have a query where I'd like to combine the free text nature of .QueryString with the range operations of .DateRange in the same resultset.

I was looking at how to combine queries and it looks like you can use the bool operator, but I can't find an example of combining .QueryString and .DateRange.

Is what I want to do possible?

Thanks!

Hi @mccamike, the bool query is typically used to combine multiple queries together in order to calculate an overall score for matching documents.

Typically with range queries, the answer to whether a document matches is a simple yes/no i.e. does the document field fall within the input range or not? These kinds of queries can be placed in a bool query filter clause. For full-text queries such as query_string query where a score is calculated for a document based on how well it matches the input query, these are typically placed in the must clause. Putting this altogether

var client = new ElasticClient();

var response = client.Search<MyDocument>(s => s
	.Query(q => q
		.Bool(b => b
			.Must(mu => mu
				.QueryString(qs => qs
					.Fields(f => f
						.Fields("field1", "field2")
					)
					.Query("my query string input")
				)
			)
			.Filter(fi => fi
				.DateRange(d => d
					.Field("datefield")
					.GreaterThan(DateMath.Now.Subtract("7d"))
				)
			)
		)
	)
);

which produces the query

{
  "query": {
    "bool": {
      "filter": [
        {
          "range": {
            "datefield": {
              "gt": "now-7d"
            }
          }
        }
      ],
      "must": [
        {
          "query_string": {
            "fields": [
              "field1",
              "field2"
            ],
            "query": "my query string input"
          }
        }
      ]
    }
  }
}

Because writing bool queries is so common, NEST overloads operators on queries to make writing complex queries more succinct. The above query using operator overloading looks like

var response = client.Search<MyDocument>(s => s
	.Query(q => q
		.QueryString(qs => qs
			.Fields(f => f
				.Fields("field1", "field2")
			)
			.Query("my query string input")
		) && +q
		.DateRange(d => d
			.Field("datefield")
			.GreaterThan(DateMath.Now.Subtract("7d"))
		)
	)
);

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