用于精确文本匹配的查询
本文关键字:查询 文本 用于 | 更新日期: 2023-09-27 18:09:43
我正在尝试编写一个NEST查询,应该根据精确的字符串匹配返回结果。我在网上研究过,有关于使用Term, Match, MatchPhrase的建议。我已经尝试了所有这些,但我的搜索返回的结果,其中包含搜索字符串的一部分。例如,在我的数据库中,我有以下几行电子邮件地址:
ter@gmail.com
ter@hotmail.com
terrance@hotmail.com
不管我是否使用:
client.Search<Emails>(s => s.From(0)
.Size(MaximumSearchResultsSize)
.Query(q => q.Term( p=> p.OnField(fielname).Value(fieldValue))))
或
client.Search<Emails>(s => s.From(0).
Size(MaximumPaymentSearchResults).
Query(q=>q.Match(p=>p.OnField(fieldName).Query(fieldValue))));
我的搜索结果总是返回包含"部分搜索"字符串的行。
所以,如果我提供搜索字符串为"ter",我仍然得到所有3行。ter@gmail.com
ter@hotmail.com
terrance@hotmail.com
如果搜索字符串是"ter",我希望看到没有行返回。如果搜索字符串是"ter@hotmail.com",那么我只希望看到"ter@hotmail.com"。
不知道我做错了什么
根据您在问题中提供的信息,听起来包含电子邮件地址的字段已被标准分析器索引,如果没有指定其他分析器或该字段未标记为not_analyzed
,则默认分析器应用于字符串字段。
标准分析器对给定字符串输入的含义可以通过使用Elasticsearch的Analyze API看到:
curl -XPOST "http://localhost:9200/_analyze?analyzer=standard&text=ter%40gmail.com
文本输入需要url编码,如这里的@符号所示。运行此查询的结果为
{
"tokens": [
{
"token": "ter",
"start_offset": 0,
"end_offset": 3,
"type": "<ALPHANUM>",
"position": 1
},
{
"token": "gmail.com",
"start_offset": 4,
"end_offset": 13,
"type": "<ALPHANUM>",
"position": 2
}
]
}
我们可以看到,标准分析器为输入生成两个令牌,ter
和gmail.com
,这就是将存储在字段倒排索引中的内容。
现在,运行Match查询将导致对匹配查询的输入进行分析,默认情况下使用与应用匹配查询的字段的映射定义中找到的分析器相同的分析器。
在默认情况下,匹配查询分析的结果标记将合并到布尔值或查询中,这样,包含该字段的倒排索引中的任何标记的任何文档都将是匹配的。例如text ter@gmail.com
,这意味着任何与ter
或gmail.com
字段匹配的文档都将被击中
// Indexing
input: ter@gmail.com -> standard analyzer -> ter,gmail.com in inverted index
// Querying
input: ter@gmail.com -> match query -> docs with ter or gmail.com are a hit!
显然,对于精确匹配,这根本不是我们想要的!
运行Term查询将导致对而不是的术语查询的输入被分析,即它是一个与术语输入完全匹配的查询,但是在索引时已经分析过的字段上运行它可能会产生问题;由于字段的值经过了分析,但术语查询的输入没有经过分析,因此作为索引时发生的分析的结果,您将得到与术语输入完全匹配的返回结果。例如
// Indexing
input: ter@gmail.com -> standard analyzer -> ter,gmail.com in inverted index
// Querying
input: ter@gmail.com -> term query -> No exact matches for ter@gmail.com
input: ter -> term query -> docs with ter in inverted index are a hit!
这也不是我们想要的!我们可能想要对这个字段做的是在映射定义中将其设置为not_analyzed
putMappingDescriptor
.MapFromAttributes()
.Properties(p => p
.String(s => s.Name(n => n.FieldName).Index(FieldIndexOption.NotAnalyzed)
);
在此基础上,我们可以使用Filtered查询
,使用Term过滤器搜索精确匹配的// change dynamic to your type
var docs = client.Search<dynamic>(b => b
.Query(q => q
.Filtered(fq => fq
.Filter(f => f
.Term("fieldName", "ter@gmail.com")
)
)
)
);
将生成以下查询DSL
{
"query": {
"filtered": {
"filter": {
"term": {
"fieldName": "ter@gmail.com"
}
}
}
}
}
您也可以使用MatchPhrasePrefix查询来执行"精确"匹配。
.MatchPhrasePrefix(ma => ma.Field(field).Query(query))
可以将"Bool查询"匹配短语前缀查询"
var boolQuery = new BoolQueryDescriptor<MyClass>();
boolQuery.Must(must => must
.MatchPhrasePrefix(matchPhrasePrefix => matchPhrasePrefix
.Field(f => f.Title)
.Field(f => f.Description)
.Query(text)
)
);