2019年2月3日日曜日

ElasticsearchのクエリDSLでand検索

ElasticsearchのクエリDSLでのand検索

インデクスの内容


 curl -H 'Content-Type:application/json' http://localhost:9200/test_index/_search -d '{"query": {"match_all":{}}}' | jq '.hits.hits'
[
  {
    "_index": "test_index",
    "_type": "test",
    "_id": "1",
    "_score": 1,
    "_source": {
      "user_name": "test user1"
    }
  },
  {
    "_index": "test_index",
    "_type": "test",
    "_id": "2",
    "_score": 1,
    "_source": {
      "user_name": "test user2"
    }
  }
]

デフォルトでのmatchクエリ

デフォルトでは、検索条件で指定したusertest1のOR検索になるので、test user2もヒットする。

curl -H 'Content-Type:application/json' http://localhost:9200/test_index/_search -d '{"query": {"match":{"user_name": "test user1"}}}' | jq '.hits.hits'
[
  {
    "_index": "test_index",
    "_type": "test",
    "_id": "1",
    "_score": 0.87546873,
    "_source": {
      "user_name": "test user1"
    }
  },
  {
    "_index": "test_index",
    "_type": "test",
    "_id": "2",
    "_score": 0.18232156,
    "_source": {
      "user_name": "test user2"
    }
  }
]

AND検索

operatorにandを指定するとAND条件に変更でき、検索結果からuser2のデータが消える。

curl -H 'Content-Type:application/json' http://localhost:9200/test_index/_search -d '{"query": {"match":{"user_name": {"query":"test user1", "operator":"and" }}}}' | jq .hits.hits
[
  {
    "_index": "test_index",
    "_type": "test",
    "_id": "1",
    "_score": 0.87546873,
    "_source": {
      "user_name": "test user1"
    }
  }
]

その他の指定

minimum_should_matchで、指定したキーワードのうち何個マッチ以上マッチしたものを返すことができる。
この場合は、1を指定しているので1つ以上マッチしたものがヒットする

 curl -H 'Content-Type:application/json' http://localhost:9200/test_index/_search -d '{"query": {"match":{"user_name": {"query":"test user1", "minimum_should_match":1 }}}}' | jq .hits.hits
[
  {
    "_index": "test_index",
    "_type": "test",
    "_id": "1",
    "_score": 0.87546873,
    "_source": {
      "user_name": "test user1"
    }
  },
  {
    "_index": "test_index",
    "_type": "test",
    "_id": "2",
    "_score": 0.18232156,
    "_source": {
      "user_name": "test user2"
    }
  }
]