我的 elasticsearch 索引中有一些 id 值(数字和文本组合),在我的程序中,用户可能会在搜索关键字中输入一些特殊字符。我想知道无论如何可以让elasticsearch使用精确搜索并且还可以删除搜索关键字中的一些特殊字符
我已经使用自定义分析器按一些特殊字符拆分搜索关键字。并使用查询->匹配来搜索数据,但我仍然没有结果
{
"_index": "testdata",
"_type": "_doc",
"_id": "11112222",
"_source": {
"testid": "1MK444750"
}
}
"analysis" : {
"analyzer" : {
"testidanalyzer" : {
"pattern" : """([^\w\d]+|_)""",
"type" : "pattern"
}
}
}
{
"article" : {
"mappings" : {
"_doc" : {
"properties" : {
"testid" : {
"type" : "text",
"analyzer" : "testidanalyzer"
}
}
}
}
}
}
这是我的弹性搜索查询
GET /testdata/_search
{
"query": {
"match": {
// "testid": "1MK_444-750" // no result
"testid": "1MK444750"
}
}
}
和分析器成功分离了我的关键字,但我无法匹配任何结果
POST /testdata/_analyze
{
"analyzer": "testidanalyzer",
"text": "1MK_444-750"
}
{
"tokens" : [
{
"token" : "1mk",
"start_offset" : 0,
"end_offset" : 3,
"type" : "word",
"position" : 0
},
{
"token" : "444",
"start_offset" : 4,
"end_offset" : 7,
"type" : "word",
"position" : 1
},
{
"token" : "750",
"start_offset" : 8,
"end_offset" : 11,
"type" : "word",
"position" : 2
}
]
}
请帮忙,提前致谢!
首先,您可能应该将testid
字段建模为keyword
而不是text
,它是一种更合适的数据类型。
您想加入一个功能,从而在搜索时有效地忽略某些字符 ( _
, -
)。您可以通过为您的字段提供一个规范化器来实现这一点,它告诉 Elasticsearch 如何在索引或搜索之前预处理该字段的数据。具体来说,您可以在规范化器中声明一个映射字符过滤器,用空字符串替换这些字符。
这就是所有这些更改适合您的映射的方式:
PUT /testdata
{
"settings": {
"analysis": {
"char_filter": {
"mycharfilter": {
"type": "mapping",
"mappings": [
"_ => ",
"- => "
]
}
},
"normalizer": {
"mynormalizer": {
"type": "custom",
"char_filter": [
"mycharfilter"
]
}
}
}
},
"mappings": {
"_doc": {
"properties": {
"testid" : {
"type" : "keyword",
"normalizer" : "mynormalizer"
}
}
}
}
}
以下搜索将产生相同的结果:
GET /testdata/_search
{
"query": {
"match": {
"testid": "1MK444750"
}
}
}
GET /testdata/_search
{
"query": {
"match": {
"testid": "1MK_444-750"
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句