Reputation: 312
I need to get the documents from ES using NEST client with multiple like conditions on a single field.
My query is as:
SELECT * FROM Customer WHERE CustomerName LIKE '%john%' OR CustomerName Like '%george%'
My elastic search NEST query (for single like operation)is as:
var customers= ElasticSearchHelper.ElasticClient.SearchAsync<Customer>(body => body
.Take(100000)
.Filter(f => f
.And
(
fs=> fs.Query(q=> .QueryString(qs => qs
.Query("*" + SearchText + "*")
.OnField(new string[] { "FirstName"})
.DefaultOperator(Operator.or)
.MinimumShouldMatchPercentage(100)
.AnalyzeWildcard(true)))
)));
return customers.Documents;
How can I do this with multiple like operation on a single field? Please guide me what I am doing wrong.
Upvotes: 1
Views: 3834
Reputation: 1233
What you need to use is an OR filter combined with a Regex filter:
SearchDescriptor<T> searchDescriptor = new SearchDescriptor<T>();
FilterDescriptor<T> filterDescriptor = new FilterDescriptor<T>();
FilterContainer filterContainer1 = new FilterContainer();
filterContainer1 = filterDescriptor.Regexp(rg =>
rg.OnField("CustomerName").Value(".*" + "john" + ".*"));
FilterContainer filterContainer2 = new FilterContainer();
filterContainer2 = filterDescriptor.Regexp(rg =>
rg.OnField("CustomerName").Value(".*" + "george" + ".*"));
searchDescriptor.Filter(flt =>
flt.Or(filterContainer1, filterContainer2));
var resulet = this.ElasticClient().Search<T>(body => searchDescriptor);
Will produce the below query (T is the type of your document):
{
"filter": {
"or": {
"filters": [
{
"regexp": {
"CustomerName": {
"value": ".*john.*"
}
}
},
{
"regexp": {
"CustomerName": {
"value": ".*doe.*"
}
}
}
]
}
}
}
Upvotes: 2