ElasticSearch - 使用连字符搜索

时间:2015-06-18 13:41:35

标签: elasticsearch mapping hyphen

弹性搜索1.6

我想索引包含连字符的文本,例如U-12,U-17,WU-12,T恤......并且能够使用“简单查询字符串”查询来搜索它们。

数据样本(简化):

{"title":"U-12 Soccer",
 "comment": "the t-shirts are dirty"}

由于关于连字符的问题已经有很多,我已经尝试了以下解决方案:

使用字符过滤器:ElasticSearch - Searching with hyphens in name

所以我去了这个映射:

{
  "settings":{
    "analysis":{
      "char_filter":{
        "myHyphenRemoval":{
          "type":"mapping",
          "mappings":[
            "-=>"
          ]
        }
      },
      "analyzer":{
        "default":{
          "type":"custom",
          "char_filter":  [ "myHyphenRemoval" ],
          "tokenizer":"standard",
          "filter":[
            "standard",
            "lowercase"
          ]
        }
      }
    }
  },
  "mappings":{
    "test":{
      "properties":{
        "title":{
          "type":"string"
        },
        "comment":{
          "type":"string"
        }
      }
    }
  }
}

使用以下查询完成搜索:

{"_source":true,
  "query":{
    "simple_query_string":{
      "query":"<Text>",
      "default_operator":"AND"
    }
  }
}
  1. 什么有效:

    “U-12”,“U *”,“t *”,“ts *”

  2. 什么行不通:

    “U- *”,“u-1 *”,“t- *”,“t-sh *”,...

  3. 所以看起来字符过滤器没有在搜索字符串上执行? 我能做些什么来完成这项工作?

3 个答案:

答案 0 :(得分:6)

答案很简单:

引自Igor Motov:Configuring the standard tokenizer

  

默认情况下,simple_query_string查询不会分析单词   用通配符。因此,它会搜索以所有开头的所有令牌   我是一个。 i-mac这个词并不匹配这个请求,因为在期间   分析它分为两个令牌i和mac,这两个都没有   令牌以i-ma开头。为了使这个查询找到你的i-mac   需要让它分析通配符:

{
  "_source":true,
  "query":{
    "simple_query_string":{
      "query":"u-1*",
      "analyze_wildcard":true,
      "default_operator":"AND"
    }
  }
}

答案 1 :(得分:1)

来自Igor Motov的引用是真的,你必须添加“analyze_wildcard”:true,以使其与正则表达式一起使用。但重要的是要注意连字符实际上用“u”“12”中的“u-12”标记,两个单独的单词。

如果保留原始内容很重要,请不要使用Mapping char过滤器。否则是有用的。

想象一下你有“m0-77”,“m1-77”和“m2-77”,如果搜索m * -77,你的命中率为零。但是你可以用AND重新加上“ - ”(连字符)以连接两个分开的单词,然后搜索m * AND 77,它将为你提供正确的命中。

你可以在客户端前面做到这一点。

在你的问题中你 - *

{
  "query":{
    "simple_query_string":{
      "query":"u AND 1*",
      "analyze_wildcard":true
    }
  }
}

T-SH *

  {
      "query":{
        "simple_query_string":{
          "query":"t AND sh*",
          "analyze_wildcard":true
        }
      }
    }

答案 2 :(得分:1)

If anyone is still looking for a simple workaround to this issue, replace hyphen with underscore _ when indexing data.

For eg, O-000022334 should indexed as O_000022334.

When searching, replace underscore back to hyphen again when displaying results. This way you can search for "O-000022334" and it will find a correct match.