1
5

More than 5 years have passed since last update.

Elasticsearchの複数タグをもつドキュメントがどのように検索できるか試してみる

Posted at

senseで実行します。

indexの作成とデータの挿入

# Delete the `my_index` index
DELETE /my_index

# Create index
PUT /my_index

# Index example docs
PUT /my_index/my_type/1
{
  "tags": [
    "search"
  ],
  "tag_count": 1
}

PUT /my_index/my_type/2
{
  "tags": [
    "search",
    "open_source"
  ],
  "tag_count": 2
}

検索

searchというタグが含まれているものを検索

# クエリ
GET /my_index/my_type/_search
{
  "query": {
    "constant_score": {
      "filter": {
        "bool": {
          "must": [
            {
              "term": {
                "tags": "search"
              }
            }
          ]
        }
      }
    }
  }
}

# 結果
{
  "took": 8,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 2,
    "max_score": 1,
    "hits": [
      {
        "_index": "my_index",
        "_type": "my_type",
        "_id": "2",
        "_score": 1,
        "_source": {
          "tags": [
            "search",
            "open_source"
          ],
          "tag_count": 2
        }
      },
      {
        "_index": "my_index",
        "_type": "my_type",
        "_id": "1",
        "_score": 1,
        "_source": {
          "tags": [
            "search"
          ],
          "tag_count": 1
        }
      }
    ]
  }
}

open_sourceという単語が含まれているものの結果は以下

# クエリ
GET /my_index/my_type/_search
{
  "query": {
    "constant_score": {
      "filter": {
        "bool": {
          "must": [
            {
              "term": {
                "tags": "open_source"
              }
            }
          ]
        }
      }
    }
  }
}

# 結果
{
  "took": 1,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 1,
    "max_score": 1,
    "hits": [
      {
        "_index": "my_index",
        "_type": "my_type",
        "_id": "2",
        "_score": 1,
        "_source": {
          "tags": [
            "search",
            "open_source"
          ],
          "tag_count": 2
        }
      }
    ]
  }
}

参考

1
5
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
1
5