I want to build a query like this:
GET elasticIndexExample/_search
{
"query": {
"bool":{
"must": [
{
"range": {
"creationDate": {
"gte": "2004-08-02T05:00:00.000Z",
"lte": "2004-10-02T05:00:00.000Z",
"boost": 2.0
}
}
},
{
"bool":{
"should": [
{
"term":{
"customerName": "Wallmart"
}
},
{
"term":{
"customerName": "Petco"
}
}
],
"minimum_should_match": 1
}
},
{
"bool": {
"should": [
{
"term":{
"state": "OH"
}
},
{
"term":{
"state": "MI"
}
}
],
"minimum_should_match": 1
}
}
]
}
}
}
So this will return all records that are within a date that are either from wallmart or petco that were in Ohio or Michigan. This elastic query works, and gets exactly what I want. Only issue is I am trying to plug something like this in an API that takes in arbitray input for what states and names to plug into those bool:should arrays.
This is what I am doing now (for only one should array, the other is the same)
// This list will hold ALL should queries
List<QueryDescriptor<ElasticLoad>> shouldQueryList = new();
QueryDescriptor<ElasticLoad> customerNamesShouldQuery = new();
if (customerPOs.Count > 0)
{
customerNameShouldQuery .Bool(boolQuery =>
boolQuery.Should(should =>
{
foreach (var customerName in customerNames)
{
should.Term(term =>
term.Field(field => field.CustomerName).Value(CustomerName)
);
}
})
.MinimumShouldMatch(1);
);
shouldQueryList.Add(customerNamesShouldQuery);
}
var lookAtShouldQueryList = client.RequestResponseSerializer.SerializeToString(
shouldQueryList,
formatting: Elastic.Transport.SerializationFormatting.Indented
);
return shouldQueryList;
but when I look at the json at the end I only see the last term added (so when I pass [“wallmart”, “petco”] it makes (NOTE: Missing petco):
"bool":{
"should": [
{
"term":{
"customerName": "Wallmart"
}
}
],
"minimum_should_match": 1
}
how can I dynamically add those term queries to the bool query in the foreach loop? (or if that is an x y delema, how should I go about this differently)
Thank you in advance! 🙂