你可以的,加油

查询结果按照输入词的匹配个数排序

Elasticsearch | 作者 id401876 | 发布于2020年06月19日 | 阅读数:1418

输入 A  B  C  D
内容都是用空格分隔的,分词器选的是whitespace
得到结果:
1、G  B  C  D  A  E  F            (包含4个输入词)
2、M N  L  P  T  A  C  D       (包含3个输入词)
3、M  C  D                           (包含2个输入词)
4、D                                    (包含1个输入词)
期望的排序是  1  → 2  →  3 →  4  (实际不是)

请问如何写查询?
已邀请:

FFFrp

赞同来自:

function score 写个脚本,包含1个得加1分,直接用这个分数排序

murphy

赞同来自:

直觉上命中的term越多的文档越相关,所以,做了一下测试,结果是符合期望的。文档排序是1, 2, 3, 4。
排序不一致,有可能是score计算不够准确。
 
解决方法:
1. "number_of_shards": "1"
2. 如果shard数量大于1,需要使用search_type来提高score准确性。
    /whitespace_example/_search?search_type=dfs_query_then_fetch
 
环境准备:Elasticsearch版本为:6.8.10
curl -XPUT /whitespace_example -H "Content-Type: application/json" -d '{
"settings": {
"number_of_shards": "1",
"analysis": {
"analyzer": {
"my_analyzer": {
"tokenizer": "whitespace",
"filter": []
}
}
}
},
"mappings": {
"_doc": {
"properties": {
"title": {
"type": "text",
"analyzer": "my_analyzer"
}
}
}
}
}'

curl -XPUT /whitespace_example/_doc/1 -H "Content-Type: application/json" -d '{
"content": "G B C D A E F"
}'

curl -XPUT /whitespace_example/_doc/2 -H "Content-Type: application/json" -d '{
"content": "M N L P T A C D"
}'

curl -XPUT /whitespace_example/_doc/3 -H "Content-Type: application/json" -d '{
"content": "M C D"
}'

curl -XPUT /whitespace_example/_doc/4 -H "Content-Type: application/json" -d '{
"content": "D"
}'


查询:
curl -XGET /whitespace_example/_search -H "Content-Type: application/json" -d '{
"query": {
"match": {
"content": "A B C D"
}
}
}'

 
结果:
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 4,
"max_score": 1.9762064,
"hits": [
{
"_index": "whitespace_example",
"_type": "_doc",
"_id": "1",
"_score": 1.9762064,
"_source": {
"content": "G B C D A E F"
}
},
{
"_index": "whitespace_example",
"_type": "_doc",
"_id": "2",
"_score": 0.9025539,
"_source": {
"content": "M N L P T A C D"
}
},
{
"_index": "whitespace_example",
"_type": "_doc",
"_id": "3",
"_score": 0.5440305,
"_source": {
"content": "M C D"
}
},
{
"_index": "whitespace_example",
"_type": "_doc",
"_id": "4",
"_score": 0.15562083,
"_source": {
"content": "D"
}
}
]
}
}

要回复问题请先登录注册