如何有条件地在 ElasticSearch 中添加多个条件?
how to add multiple conditions in ElasticSearch conditionally?
针对以下过滤器查询:
var searchResults = _client.Search<MyIndexable>(s => s
.Query(q => q
.Bool(b => b
.Must(
subQuery => subQuery.QueryString(qs => qs.OnFields(f => f.Title, f => f.Description).Query(searchTerm + "*"")),
subQuery => subQuery.Term(f => f.field1, "some string"),
subQuery => subQuery.Term(f => f.field2 , "some Guid")))));
我想在“必须”下有条件地添加下面的每个过滤器。喜欢
if (request.field2)
ubQuery.Term(f => f.field1, "some string"
谁能帮我做这个?
由于方法链接,这对你来说很难。
在json中设置配置更方便。因为json是一个字符串,所以打断和插入条件等都很简单
示例:
$config = '{
"query":
{';
if (condition) {
$config .= '"match":
{
"foo": "bar"
}';
}
$config .= '
}
}';
当然,您可以自由选择构建json字符串的方式。
可以在Nest中完成。请看下面的代码:
var funcs = new List<Func<QueryDescriptor<MyIndexable>, QueryContainer>>();
funcs.Add(subQuery.QueryString(qs => qs.OnFields(f => f.Title, f => f.Description).Query(searchTerm + "*"")));
if (request.field2) // I believe this is some bool variable
{
funcs.Add(subQuery => subQuery.Term(f => f.field1, "some string"));
}
funcs.Add(subQuery => subQuery => subQuery.Term(f => f.field2 , "some Guid"));
var searchResults = _client.Search<MyIndexable>(s => s
.Query(q => q
.Bool(b => b
.Must(funcs.ToArray()))));
针对以下过滤器查询:
var searchResults = _client.Search<MyIndexable>(s => s
.Query(q => q
.Bool(b => b
.Must(
subQuery => subQuery.QueryString(qs => qs.OnFields(f => f.Title, f => f.Description).Query(searchTerm + "*"")),
subQuery => subQuery.Term(f => f.field1, "some string"),
subQuery => subQuery.Term(f => f.field2 , "some Guid")))));
我想在“必须”下有条件地添加下面的每个过滤器。喜欢
if (request.field2)
ubQuery.Term(f => f.field1, "some string"
谁能帮我做这个?
由于方法链接,这对你来说很难。
在json中设置配置更方便。因为json是一个字符串,所以打断和插入条件等都很简单
示例:
$config = '{
"query":
{';
if (condition) {
$config .= '"match":
{
"foo": "bar"
}';
}
$config .= '
}
}';
当然,您可以自由选择构建json字符串的方式。
可以在Nest中完成。请看下面的代码:
var funcs = new List<Func<QueryDescriptor<MyIndexable>, QueryContainer>>();
funcs.Add(subQuery.QueryString(qs => qs.OnFields(f => f.Title, f => f.Description).Query(searchTerm + "*"")));
if (request.field2) // I believe this is some bool variable
{
funcs.Add(subQuery => subQuery.Term(f => f.field1, "some string"));
}
funcs.Add(subQuery => subQuery => subQuery.Term(f => f.field2 , "some Guid"));
var searchResults = _client.Search<MyIndexable>(s => s
.Query(q => q
.Bool(b => b
.Must(funcs.ToArray()))));