k16
k16

Reputation: 481

How can I sort the result of Elasticsearch suggest?

I am using the Elasticsearch suggest function. And I want to sort the result.

For instance, I want to index like these datas to the Elasticsearch.

| itemname  | total_pv  |
| Apple     | 100       |
| Lemon     | 200       |
| Orange    | 50        |
| Banana    | 120       |
| Lime      | 100       |

When users input "L" in the input tags, I want to sort the result as "total_pv". In this case, the order "Lemon", "Lime" is what I want.

It is also same meaning if I write it as SQL.

SELECT itemname FROM sometable WHERE itemname LIKE 'L%' ORDER BY total_pv DESC

I have tried to index below request, but I could not get correct answer when I request to the Elasticsearch with word of "L".

{ "index" : { "_index" : "ss_suggest", "_type" : "keyword", "_id" : "8120" } }
{ "suggest" : "Apple", "weight" : "100"}
{ "index" : { "_index" : "ss_suggest", "_type" : "keyword", "_id" : "8020" } }
{ "suggest" : "Lemon", "weight" : "200"}
{ "index" : { "_index" : "ss_suggest", "_type" : "keyword", "_id" : "8021" } }
{ "suggest" : "Orange", "weight" : "50"}
{ "index" : { "_index" : "ss_suggest", "_type" : "keyword", "_id" : "8110" } }
{ "suggest" : "Banana", "weight" : "120"}
{ "index" : { "_index" : "ss_suggest", "_type" : "keyword", "_id" : "4080" } }
{ "suggest" : "Lime", "weight" : "100"}

The indexing setting is like this.

{
  "settings": {
    "analysis": {
      "filter": {
        "katakana_stemmer": {
          "type": "kuromoji_stemmer"
        },
        "katakana_readingform" : {
          "type" : "kuromoji_readingform",
          "use_romaji" : false
        }
      },
      "tokenizer": {
        "kuromoji_tokenizer": {
          "type": "kuromoji_tokenizer",
          "mode":"search",
          "user_dictionary": "user_dict.txt"
        }
      },
      "analyzer": {
        "kuromoji_analyzer": {
          "type":"custom",
          "tokenizer":"kuromoji_tokenizer",
          "char_filter":["html_strip", "kuromoji_iteration_mark",    "icu_normalizer"],
          "filter": ["lowercase", "cjk_width", "katakana_stemmer", "kuromoji_part_of_speech", "kuromoji_baseform", "katakana_readingform"]
        }
      }
    }
  },
  "mappings": {
    "keyword": {
      "properties": {
        "suggest": {
          "type": "completion",
          "index_analyzer": "kuromoji_analyzer",
          "search_analyzer": "kuromoji_analyzer"
        }
      }
    }
  }
}

And then the search query is like this.

{
  "index": "ss_suggest",
  "body": {
    "keyword": {
      "text": "L",
      "completion": {
        "field": "suggest"
      }
    }
  }
}

Could anyone tell me how can I do it ?
Thanks.

Upvotes: 1

Views: 924

Answers (1)

k16
k16

Reputation: 481

I got the answer. The format should be like this.

{ "index" : { "_index" : "ss_suggest", "_type" : "keyword", "_id" : "8120" } }    
{ "suggest" : { "input" : "Apple", "weight" : "100" } }

Upvotes: 1

Related Questions