0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Elasticsearch:"_id" でソートする方法

Last updated at Posted at 2022-12-21

Elasticsearchのクエリ検索結果を「_idでソートする方法」についてまとめました。

環境

Elasticsearch:7.3.2

検索結果のソート

Elasticsearchでは、検索結果をソートした形で受け取ることができます。
例えば、カラムnumberで昇順ソートしたい場合は以下のようになります。

GET /{index_name}/_search
{
    "query": {
        "match_all": {}
    },
     "sort" : [{"number":"asc"}]
}

idでソートするのにハマった

Elasticsearchでは特に指定がない場合、各ドキュメントへ_idが自動生成されます。
以下のように_idでソートしてみた...

GET /{index_name}/_search
{
    "query": {
        "match_all": {}
    },
     "sort" : [{"_id":"asc"}]
}

結果、全然うまくソートされていない...
どうやら、自動生成された_idはstring型らしい。

MySQLのcastみたいな方法はないのか。
全然ドキュメント見つからない。

解決方法

中国語で書かれたサイトで解決策を見つけました。
_idに基づくソートは以下のように書けるらしい。

GET /{index_name}/_search
{
  query: {
    match_all: {}
   },
  sort: {
    _script: {
      type: 'number',
      script: "Integer.parseInt(doc['_id'].value)",
      order: 'desc'
    }
   }
 }

この方法は、テキスト数字のソートへ汎用的に使えそうですね!

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?