elasticsearch 在NEST中,如何从术语列表动态构建查询?
假设我的用户提供了我收集到数组/列表中的搜索词列表,现在我想使用MatchPhrase将这些或wise组合到嵌套查询中。我该怎么做?(单个)搜索词的代码如下所示:elasticsearch 在NEST中,如何从术语列表动态构建查询?,elasticsearch,nest,elasticsearch,Nest,假设我的用户提供了我收集到数组/列表中的搜索词列表,现在我想使用MatchPhrase将这些或wise组合到嵌套查询中。我该怎么做?(单个)搜索词的代码如下所示: var search=client.search(s=>s .Query(q=> q、 匹配短语(m=>m.OnField(f=>f.Title).Query(term.ToLower()).Slop(Slop)) ||匹配短语(m=>m.OnField(f=>f.Description).Query(text.Slop(Slop))
var search=client.search(s=>s
.Query(q=>
q、 匹配短语(m=>m.OnField(f=>f.Title).Query(term.ToLower()).Slop(Slop))
||匹配短语(m=>m.OnField(f=>f.Description).Query(text.Slop(Slop))
)
.LowercaseeExpandedTerms()
.解释
.Query(q=>q.Fuzzy(f=>f.PrefixLength(1).OnField(c=>c.Title).OnField(c=>c.Description)))
);
这很好,但我需要为每个提供的搜索词应用相同的匹配短语过滤器一次。非常感谢您的帮助。您可以使用
bool
should
表达式动态构建查询。我将在下面提供完整的解决方案。使用适当的参数调用BuildQuery()
方法
ISearchResponse构建查询(IElasticClient客户端,IEnumerable术语,int-slop)
{
返回client.Search(s=>s
.Query(q=>q
.Bool(b=>b
.Should(terms.Select(t=>BuildPhraseQueryContainer(q,t,slop)).ToArray())
.LowercaseeExpandedTerms()
.解释
.Query(q=>q.Fuzzy(f=>f.PrefixLength(1).OnField(c=>c.Title).OnField(c=>c.Description));
}
QueryContainer构建语法QueryContainer(QueryDescriptor qd,字符串术语,int-slop)
{
返回qd.MatchPhrase(m=>m.OnField(f=>f.Title).Query(term.ToLower()).Slop(Slop))||
匹配短语(m=>m.OnField(f=>f.Description).Query(term.ToLower()).Slop(Slop));
}
对于terms={“term1”、“term2”、“term3”}
和slop=0
,将由我的代码生成的Elasticsearch JSON命令如下所示:
{
"explain": true,
"query": {
"bool": {
"should": [
{
"bool": {
"should": [
{
"match": {
"title": {
"type": "phrase",
"query": "term1",
"slop": 0
}
}
},
{
"match": {
"description": {
"type": "phrase",
"query": "term1",
"slop": 0
}
}
}
]
}
},
{
"bool": {
"should": [
{
"match": {
"title": {
"type": "phrase",
"query": "term2",
"slop": 0
}
}
},
{
"match": {
"description": {
"type": "phrase",
"query": "term2",
"slop": 0
}
}
}
]
}
},
{
"bool": {
"should": [
{
"match": {
"title": {
"type": "phrase",
"query": "term3",
"slop": 0
}
}
},
{
"match": {
"description": {
"type": "phrase",
"query": "term3",
"slop": 0
}
}
}
]
}
}
]
}
}
}
您可以调整此代码,使所有
match
命令都位于相同的should
节点下。我会让你自己去弄清楚:)非常感谢你的详尽回答!这是一个奇妙的答案。NEST v 5.2抛出异常“querycontainer只能保存一个已经包含matchphrasequerydescriptor的查询”。