The project uses functions to part by part create an ElasticSearch query. In this case, the final query would look like this:
{
"_source": true,
"from": 0,
"size": 0,
"sort": [],
"aggs": {
"body": {
"nested": {
"path": "preparers"
},
"aggs": {
"body": {
"terms": {
"field": "preparers.employee.id",
"size": 1000,
"order": {
"_count": "desc"
},
"include": "-1097",
"min_doc_count": 0
}
}
}
}
}
}
Here is the function currently used to add the terms
part of the query:
public void AddTerms(string field, int size, int minDocCount = 1, string orderBy = "_count", string order = "desc", string missing = "")
{
var str = new StringBuilder();
if (missing.Length > 0)
str.Append($"\"terms\": {{ \"field\": \"{field}\", \"size\": {size}, \"order\": {{ \"{orderBy}\": \"{order}\" }}, \"missing\": \"{missing}\", \"min_doc_count\": {minDocCount} }}");
else
str.Append($"\"terms\": {{ \"field\": \"{field}\", \"size\": {size}, \"order\": {{ \"{orderBy}\": \"{order}\" }}, \"min_doc_count\": {minDocCount} }}");
_aggregation_body = str.ToString();
}
Currently this function does not add the include
property to the terms
object, so I need to add it. So my first idea was to add else if
like so:
public void AddTerms(string field, int size, int minDocCount = 1, string orderBy = "_count", string order = "desc", string missing = "", string include = "")
{
var str = new StringBuilder();
if (missing.Length > 0)
str.Append($"\"terms\": {{ \"field\": \"{field}\", \"size\": {size}, \"order\": {{ \"{orderBy}\": \"{order}\" }}, \"missing\": \"{missing}\", \"min_doc_count\": {minDocCount} }}");
else if (include.Length > 0)
str.Append($"\"terms\": {{ \"field\": \"{field}\", \"size\": {size}, \"order\": {{ \"{orderBy}\": \"{order}\" }}, \"include\": \"{include}\", \"min_doc_count\": {minDocCount} }}");
else
str.Append($"\"terms\": {{ \"field\": \"{field}\", \"size\": {size}, \"order\": {{ \"{orderBy}\": \"{order}\" }}, \"min_doc_count\": {minDocCount} }}");
_aggregation_body = str.ToString();
}
What worries me is that include
will be necessary very rarely. It will be contained in maybe 1 out of each 100,000 searches (and each search will have many terms
properties). So that else if
will almost always evaluate to false.
So is there perhaps a better way how to add the include
to the query? Or is this not a big deal?
I thought of maybe calling the existing AddTerms()
, then trimming off the last bracket and adding include
, but that can cause issues if the returned string is somehow changed (although this seems unlikely).
Json.Net
orSystem.Text.Json
would safe you the hassle. \$\endgroup\$