在弹性搜索中,搜索精确单词和同时包含单词有什么解决方案吗


index: process.env.elasticSearchIndexName,
body: {
query: {
bool: {
must: [
{
match_phrase: {
title: `${searchKey}`,
},
},
],
},
},
},
from: (page || constants.pager.page),
size: (limit || constants.pager.limit),

我使用上面的方法,但问题是它只搜索全文中完全匹配的单词。它无法搜索包含单词。。例如,如果title="运动衫",而不是如果我键入单词"衬衫",它应该会得到结果,但目前使用上述方法没有得到结果

标准分析器(如果未指定默认分析器,则为默认分析器(在标记中打断文本。对于句子"这是一个测试",生成的标记是[this,is,a,test]Match_pharse查询使用和索引分析器相同的分析器来中断令牌中的文本,并返回1的文档。包含所有令牌2。令牌按相同顺序出现。

由于您的文本是运动衫,因此在反向索引中有一个标记"运动衫",它与汗水或衬衫都不匹配

NGram令牌化器

ngram标记器首先在遇到指定字符列表中的一个时将文本分解为单词,然后发出指定长度的每个单词的N克

映射

PUT my_index
{
"settings": {
"analysis": {
"analyzer": {
"my_analyzer": {
"tokenizer": "my_tokenizer"
}
},
"tokenizer": {
"my_tokenizer": {
"type": "ngram",
"min_gram": 3,
"max_gram": 3,
"token_chars": [
"letter",
"digit"
]
}
}
}
},
"mappings": {
"properties": {
"text":{
"type": "text",
"analyzer": "my_analyzer"
}
}
}
}

查询:

{
"query": {
"match": {
"text": "shirt"
}
}
}

如果要运行分析查询(_A(

GET my_index/_analyze
{
"text": ["sweatshirt"],
"analyzer": "my_analyzer"
}

您将看到下面的令牌是为文本运动衫生成的。代币大小可以使用min_gram和max_gram 进行调整

{
"tokens" : [
{
"token" : "swe",
"start_offset" : 0,
"end_offset" : 3,
"type" : "word",
"position" : 0
},
{
"token" : "wea",
"start_offset" : 1,
"end_offset" : 4,
"type" : "word",
"position" : 1
},
{
"token" : "eat",
"start_offset" : 2,
"end_offset" : 5,
"type" : "word",
"position" : 2
},
{
"token" : "ats",
"start_offset" : 3,
"end_offset" : 6,
"type" : "word",
"position" : 3
},
{
"token" : "tsh",
"start_offset" : 4,
"end_offset" : 7,
"type" : "word",
"position" : 4
},
{
"token" : "shi",
"start_offset" : 5,
"end_offset" : 8,
"type" : "word",
"position" : 5
},
{
"token" : "hir",
"start_offset" : 6,
"end_offset" : 9,
"type" : "word",
"position" : 6
},
{
"token" : "irt",
"start_offset" : 7,
"end_offset" : 10,
"type" : "word",
"position" : 7
}
]
}

警告:Ngrams会增加反向索引的大小,因此使用适当的min_gram和max_gram 值

另一种选择是使用通配符查询。对于通配符,必须扫描所有文档以检查文本是否与模式匹配。它们的性能很低。在未分析的字段上使用通配符搜索时,以防您希望包含空白(例如文本(。关键字

{
"query": {
"wildcard": {
"text": {
"value": "*shirt*"
}
}
}
}

最新更新