查找字段以(ElasticSearch)nodejs客户端开头的项目

时间:2019-03-06 10:13:21

标签: elasticsearch

我试图查询我的ElasticSearch索引,以便检索“ foo”字段之一以“ hel”开头的项目。

toto字段是关键字类型:

"toto": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          }

这是我尝试过的:

  client.search({index: 'xxxxx',  type: 'xxxxxx_type', body: {"query": {"regexp": {"toto": "hel.*"}}}},
  function(err, resp, status) {
    if (err)
      res.send(err)
    else {
      console.log(resp);
      res.send(resp.hits.hits)
    }
  });

我试图在这里找到解决方案:

  

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-regexp-query.html

  

https://www.elastic.co/guide/en/elasticsearch/guide/current/_wildcard_and_regexp_queries.html

或这里

  

How to search for a part of a word with ElasticSearch

但没有任何作用。

这是我的数据的样子:

{
  "took": 1,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 4,
    "max_score": 1,
    "hits": [
      {
        "_index": "xxxxxx",
        "_type": "xxxxx_type",
        "_id": "1",
        "_score": 1,
        "_source": {
              "toto": "hello"
        }
    }
}

2 个答案:

答案 0 :(得分:0)

Match phrase prefix query是您要寻找的。

使用以下查询:

{
  "query": {
    "match_phrase_prefix": {
      "toto": "hel"
    }
  }
}

答案 1 :(得分:0)

听起来您正在寻找一种自动完成的解决方案。运行正则表达式会搜索用户键入效率不高的每个字符。

我建议更改索引标记器和分析器,以便提前创建前缀标记并允许更快的搜索。

一些有关如何实现自动完成的选项: Elasticsearch完成建议:https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-suggesters-completion.html

或自己做: https://hackernoon.com/elasticsearch-building-autocomplete-functionality-494fcf81a7cf

How to suggest (autocomplete) next word in elastic search?