Elasticsearch 找不到独立的保留字符

Elasticsearch cannot find standalone reserved characters

我使用 Kibana 执行查询 elastic (Query string query)。

当我搜索包含转义字符的字词时(保留字符,例如:'\'、'+'、'-'、'&&'、'||'、'!'、'('、')' , '{', '}', '[', ']', '^', '"', '~', '*', '?', ':', '/')。它会得到预期结果。 我的示例使用:'!'

但是当我搜索单个保留字符时。我一无所获。 或者:

如何使用单个保留字符进行搜索?

Standard analyzer

The standard analyzer is the default analyzer which is used if none is specified. It provides grammar based tokenization (based on the Unicode Text Segmentation algorithm, as specified in Unicode Standard Annex #29) and works well for most languages.

因此没有为连字符生成标记。如果要查找带连字符的文本,需要查看关键字字段并使用通配符进行全文匹配

{
  "query": {
     "query_string": {
       "query": "*\-*"
     }
  }
}

TL;DR 您需要指定一个分析器(+ 一个分词器),以确保像 ! 这样的特殊字符不会在摄取阶段被剥离。


在第一个屏幕截图中,您已正确尝试 运行 _analyze。让我们利用它来发挥我们的优势。

请注意,当您未指定任何分析器时,ES 将默认为 standard analyzer which is, by definition, constrained by the standard tokenizer,它将去除所有特殊字符(撇号 ' 和其他一些字符除外)。

运行

GET dev_application/_analyze?filter_path=tokens.token
{
  "tokenizer": "standard",
  "text": "Se, det ble grønt ! a"
}

因此产生:

["Se", "det", "ble", "grønt", "a"]

这意味着您需要使用一些其他的分词器来保留这些字符。有一个few built-in ones available, the simplest of which would be the whitespace tokenizer.

运行

GET _analyze?filter_path=tokens.token
{
  "tokenizer": "whitespace",
  "text": "Se, det ble grønt ! a"
}

保留!:

["Se,", "det", "ble", "grønt", "!", "a"]

所以,

1。删除索引:

DELETE dev_application

2。然后重新设置映射:

(我选择了 multi-field approach,它将保留原始的标准分析器,并且只在 name.splitByWhitespace 子字段上应用 whitespace 分词器。)

PUT dev_application
{
  "settings": {
    "index": {
      "analysis": {
        "analyzer": {
          "splitByWhitespaceAnalyzer": {
            "tokenizer": "whitespace"
          }
        }
      }
    }
  },
  "mappings": {
    "properties": {
      "name": {
        "type": "text",
        "fields": {
          "splitByWhitespace": {
            "type": "text",
            "analyzer": "splitByWhitespaceAnalyzer"
          }
        }
      }
    }
  }
}

3。重建索引

POST dev_application/_doc
{
  "name": "Se, det ble grønt ! a"
}

4。自由搜索特殊字符:

GET dev_application/_search
{
  "query": {
    "query_string": {
      "default_field": "name.splitByWhitespace", 
      "query": "*\!*",
      "default_operator": "AND"
    }
  }
}

请注意,如果您将 default_field 排除在外,它将无法工作,因为 standard 分析器。

实际上,您可以颠倒这种方法,默认应用 whitespace,并为“原始”索引策略创建多字段映射(-> 唯一的配置是 "type": "text").


无耻外挂:我写了一个book on Elasticsearch,你可能会觉得有用!