0
votes

I'm trying to query my ElasticSearch index in order to retrieve the items that one of the "foo" fields starts with "hel".

The toto field is a keyword type:

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

This what I tried:

  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)
    }
  });

I tried to find a solution here:

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

and

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

or here

How to search for a part of a word with ElasticSearch

but nothing work.

This is how looks my data:

{
  "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

2 Answers

0
votes

Match phrase prefix query is what you are looking for.

Use the query below:

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

It sounds like you are looking for an auto-complete solution. running regex searches for every character the user type is not that efficient.

I would suggest changing the indexing tokenizers and analyzer in order to create the prefix tokens in advance and allow faster search.

Some options on how to implement auto complete: Elasticsearch Completion suggester: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-suggesters-completion.html

or do it yourself: https://hackernoon.com/elasticsearch-building-autocomplete-functionality-494fcf81a7cf

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