How to search in elasticsearch using prefix?


(Petr Sokolnikov) #1

Hello. I'm newbie in elasticsearch. Before I used Sphinx, and now decide to learn elasticsearch.

So, I have some index named test, and type named country with several documents.

I have run first query:

curl -XGET 'http://localhost:9200/test/country/_search?pretty=true' -d '
{
 "query": {
   "match": {
     "country": "Ukraine"
    }
  }
}'

And have received answer:

{
  "took" : 33,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 1,
    "max_score" : 0.24701709,
    "hits" : [ {
      "_index" : "test",
      "_type" : "country",
      "_id" : "AU-xLqS2KzVZz9Yq1Hgw",
      "_score" : 0.24701709,
      "_source":{"langId":1,"langUrl":"ru","langActive":1,"countryId":2,"countryUrl":"ukraine","countryActive":1,"country":"Ukraine"}

So, it is works correct. But now I want to search using prefix 'Ukra':

curl -XGET 'http://localhost:9200/test/country/_search?pretty=true' -d '
{
 "query": {
   "prefix": {
     "country": "Ukra"
    }
  }
}'

But have received answer without result:

{
  "took" : 5,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 0,
    "max_score" : null,
    "hits" : [ ]
  }
}

Why it is not work? What I doing wrong? I have used example from documentation https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-prefix-query.html


(David Pilato) #2

because prefix queries are not analyzed.

You have indexed ukraine behind the scene so Ukra does not match.

Try with ukra.


(Nik Everett) #3

You could also specify the analyzer for country as keyword and then your original query would work. See the [create index][https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html#mappings] api's section on mappings for one way to do this.

Elasticsearch's defaults are pretty friendly to full text search against English text using the match query. How your documents are analyzed into terms and which queries analyze their terms is super important to understand. I don't have a handy link for that but reply if you can't find one.


(Petr Sokolnikov) #4

Thank you, "ukra" does work.


(system) #5