首页 > 解决方案 > 如何在elasticsearch simple_query_string中包含除空格之外的所有字符?

问题描述

我正在寻找弹性搜索中最简单的查询系统,其中唯一的分隔符是空格。我想查询带有几乎所有类型字符的文本中的用户名,例如@username 或@u$er-na_me

它认为这很容易,但经过长时间的搜索,我发现了一个“空白”分析器:

query.json:

{
  "query": {
    "simple_query_string" : {
        "query": "@username",
        "fields": ["mytextfield"],
        "analyzer": "whitespace",
        "default_operator": "and"
    }
  }
}

其中,我运行:curl -X POST "http://localhost:9200/my.index/_search?pretty" -H 'Content-Type: application/json' -d '@query.json'

但是,它什么也不返回。

其他详情:

因此,总而言之,是否有任何简单的方法可以配置弹性搜索或查询以仅使用空格(以及理想的基本标点符号)进行标记?

标签: elasticsearch

解决方案


toto_tico,您需要分析您的字段并在您的映射中指定它,如下所示:

1) 使用单个分析字段创建索引:

PUT totoindex
{
  "mappings": {
      "_doc": {
        "properties": {
          "mytextfield":{"type":"text", "analyzer": "whitespace"}
        }
      }
    }
}

2)索引一些示例文档:

POST totoindex/_doc/
{
  "mytextfield": "@toto_tico"
}

3)搜索文档:

POST totoindex/_doc/_search
{
  "query": {
    "simple_query_string" : {
        "query": "@toto_tico",
        "fields": ["mytextfield"]
    }
  }
}

回复 :

{
  "took": 12,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 1,
    "max_score": 0.2876821,
    "hits": [
      {
        "_index": "totoindex",
        "_type": "_doc",
        "_id": "MtorKW8BavUEUOqEr6k_",
        "_score": 0.2876821,
        "_source": {
          "mytextfield": "@toto_tico"
        }
      }
    ]
  }
}

推荐阅读