我一直在寻找这类问题好几天了,但没有成功。我遵循了this和this之类的步骤,但没有成功。
因此,基本上,我在ElasticSearch上具有以下数据:
{ title: "Black Dust" },
{ title: "Dust In The Wind" },
{ title: "Gold Dust Woman" },
{ title: "Another One Bites The Dust" }
问题是我想按“尘”字搜索,并且希望结果按如下顺序排序:{ title: "Dust In The Wind" },
{ title: "Black Dust" },
{ title: "Gold Dust Woman" },
{ title: "Another One Bites The Dust" }
其中“灰尘”必须出现在结果的顶部。发布映射和查询比继续解释问题本身更好。
settings: {
analysis: {
normalizer: {
lowercase: {
type: 'custom',
filter: ['lowercase']
}
}
}
},
mappings: {
_doc: {
properties: {
title: {
type: 'text',
analyzer: 'standard',
fields: {
raw: {
type: 'keyword',
normalizer: 'lowercase'
},
fuzzy: {
type: 'text',
},
},
}
}
}
}
我的查询是:"query": {
"bool": {
"must": {
"query_string": {
"fields": [
"title"
],
"default_operator": "AND",
"query": "dust"
}
},
"should": {
"prefix": {
"title.raw": "dust"
}
}
}
}
有人可以帮我吗?谢谢!
解决方案!
我知道了,并通过执行以下查询解决了:
"query": {
"bool": {
"must": {
"bool": {
"should": [
{
"prefix": {
"title.raw": {
"value": "dust",
"boost": 1000000
}
}
},
{
"match": {
"title": {
"query": "dust",
"boost": 50000
}
}
},
{
"match": {
"title": {
"query": "dust",
"boost": 10,
"fuzziness": 1
}
}
}
]
}
}
}
}
但是,在编写测试时,我发现了一个小问题。因此,我正在生成一个随机的
uuid
并将以下内容添加到数据库中:{ title: `${uuid} A` }
{ title: `${uuid} W` }
{ title: `${uuid} Z` }
{ title: `A ${uuid}` }
{ title: `z ${uuid}` }
{ title: `Z ${uuid}` }
当我执行上面的查询以寻找uuid
时,我得到:uuid Z
uuid A
uuid W
Z uuid
我实现了第一个目标,即将uuid
置于第一个位置,但是为什么Z在A之前呢? (第一和第二结果)
最佳答案
当其他所有方法都失败时,您可以像下面这样使用琐碎的子字符串位置排序:
{
"query": {
"bool": {
"must": {
...
},
"should": {
...
}
}
},
"sort": [
{
"_script": {
"script": "return doc['title.raw'].value.indexOf('dust')",
"type": "number",
"order": "asc" <--
}
}
]
}
我将顺序设置为asc
,因为子字符串索引越低,“得分”越高。编辑
我们必须考虑
index == -1
,因此将上面的脚本替换为:"script": "def pos = doc['title.raw'].value.indexOf('dust'); return pos == -1 ? Integer.MAX_VALUE : pos"
关于elasticsearch - ElasticSearch 6.8不会先按完全匹配进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64489109/