see*_*per 5 elasticsearch nest
假设我的用户提供了我收集到数组/列表中的搜索词列表,现在我想使用MatchPhrase将这些词组合成一个NEST查询.我该怎么办?(单个)搜索词的代码如下所示:
var search = client.Search<ElasticRequirement>(s => s
.Query(q =>
q.MatchPhrase(m => m.OnField(f => f.Title).Query(term.ToLower()).Slop(slop))
|| q.MatchPhrase(m => m.OnField(f => f.Description).Query(text).Slop(slop))
)
.LowercaseExpandedTerms()
.Explain()
.Query(q => q.Fuzzy(f => f.PrefixLength(1).OnField(c => c.Title).OnField(c => c.Description)))
);
Run Code Online (Sandbox Code Playgroud)
这很好,但我需要为每个提供的搜索词应用相同的MatchPhrase过滤器一次.任何帮助非常感谢.
bit*_*kar 11
您可以使用bool should表达式动态构建查询.我将在下面提供完整的解决方案.BuildQuery()使用适当的参数调用方法.
ISearchResponse<ElasticRequirement> BuildQuery(IElasticClient client, IEnumerable<string> terms, int slop)
{
return client.Search<ElasticRequirement>(s => s
.Query(q => q
.Bool(b => b
.Should(terms.Select(t => BuildPhraseQueryContainer(q, t, slop)).ToArray())))
.LowercaseExpandedTerms()
.Explain()
.Query(q => q.Fuzzy(f => f.PrefixLength(1).OnField(c => c.Title).OnField(c => c.Description))));
}
QueryContainer BuildPhraseQueryContainer(QueryDescriptor<ElasticRequirement> qd, string term, int slop)
{
return qd.MatchPhrase(m => m.OnField(f => f.Title).Query(term.ToLower()).Slop(slop)) ||
qd.MatchPhrase(m => m.OnField(f => f.Description).Query(term.ToLower()).Slop(slop));
}
Run Code Online (Sandbox Code Playgroud)
对于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
}
}
}
]
}
}
]
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以调整此代码,使所有match命令都在同一should节点下.我会把它留给你弄清楚:)
| 归档时间: |
|
| 查看次数: |
3295 次 |
| 最近记录: |