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.
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"))
)
)
)
)
);
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"))
)
)
);
Apache, Apache Lucene, Apache Hadoop, Hadoop, HDFS and the yellow elephant
logo are trademarks of the
Apache Software Foundation
in the United States and/or other countries.