Elasticsearch:如何返回具有搜索到的确切单词的文档,而不是返回句子中包含该单词的所有文档



我有一个名为"description"的字段(类型文本(

我有三份文件。

doc1描述=";测试";

doc2描述=";测试dsc";

doc3描述=";2021测试描述";

情况1-如果我搜索";测试";我只想要doc1

情况2-如果我搜索";测试dsc";我只想要doc2

情况3-如果我搜索";2021测试描述";我只想要doc3

但现在只有CASE 3在工作

例如CASE1不工作。如果我尝试这个查询,我有所有3个文档

GET /myindex/_search
{
"query": {
"match" : {
"Description" : "test"
}
}
}

感谢

您将在搜索中获得所有三个文档,因为默认情况下,elasticsearch对text类型字段使用标准分析器。这将把"2021 test desc"标记为

{
"tokens": [
{
"token": "2021",
"start_offset": 0,
"end_offset": 4,
"type": "<NUM>",
"position": 0
},
{
"token": "test",
"start_offset": 5,
"end_offset": 9,
"type": "<ALPHANUM>",
"position": 1
},
{
"token": "desc",
"start_offset": 10,
"end_offset": 14,
"type": "<ALPHANUM>",
"position": 2
}
]
}

因此,它将返回与上述任何令牌匹配的所有文档。


如果要搜索确切的术语,则需要更新索引映射。

您可以通过多种方式(即使用多个字段(对同一字段进行索引来更新映射。

PUT /_mapping
{
"properties": {
"description": {
"type": "text",
"fields": {
"raw": {
"type": "keyword"
}
}
}
}
}

然后重新索引数据。在此之后,您将能够使用";描述";字段为文本类型;description.raw";截至关键字类型

搜索查询:

{
"query": {
"match": {
"description.raw": "test dsc"
}
}
}

搜索结果:

"hits": [
{
"_index": "67777521",
"_type": "_doc",
"_id": "2",
"_score": 0.9808291,
"_source": {
"description": "test dsc"
}
}
]

最新更新