[015] 使用 Ruby elasticsearch 7.14 进行文档的 AND 筛选搜索

简而言之

使用Ruby的Elasticsearch客户端在Elasticsearch 7.14中操作REST API。
此外,为了比较,还将在Kibana DevTool中提供查询。

本次从索引“shakespeare”中进行“文档搜索”。
提取“text_entry”字段值包含“ACT”和“V”这两个“单词”的文档。

然而,在这里仍然只取出 Elasticsearch 的默认行为的10个项目。
如果想要获取全部项目,请参考 [035]。

验证环境

検証用の数据”Shakespeare”已在下面的步骤中注册:
使用Elasticsearch + Kibana (7.14)。

使用 Ruby 的 Elasticsearch 客户端包尝试操作 Elasticsearch 7.14 … 验证环境搭建部分。

参考信息

实践

在使用Kibana DevTool时。

代码

GET shakespeare/_search
{
  "query": {
    "query_string": { 
      "query": "text_entry:ACT AND text_entry:V"
    }
  }
}

结果

image.png

在Ruby的情况下

程式碼

在中文中,重要的部分是「if __FILE__ == $0之后」。

我的简单客户端类可以直接复制,但需要适当更改其中的192.168.10.115。

#!/usr/bin/env ruby
# -*- encoding: utf-8 -*-
require 'multi_json'
require 'faraday'
require 'elasticsearch/api'
require 'active_support/core_ext' #! note_0004
require 'active_support' #! note_0005

class MySimpleClient
# note_0001
  include Elasticsearch::API
  CONNECTION = ::Faraday::Connection.new url: 'http://192.168.10.115:29200'
  def perform_request(method, path, params, body, headers = nil)
    #! note_0003
    CONNECTION.run_request \
      method.downcase.to_sym,
      path_with_params(path, params),
      (body ? MultiJson.dump(body): nil),
      {'Content-Type' => 'application/json'}
  end

  private

  def path_with_params(path, params)
    return path if params.blank?

    case params
    when String
      "#{path}?#{params}"
    when Hash
      "#{path}?#{params.to_query}"
    else
      raise ArgumentError, "Cannot parse params: '#{params}'"
    end
  end
end

if __FILE__ == $0

  client = MySimpleClient.new

  q = {
    "query": {
      # note_0006
      "query_string": { 
        "query": "text_entry:ACT AND text_entry:V"
      }
    }
  }
  res = client.search index: 'shakespeare', body: q
  h = JSON.parse(res)
  pp h
end


# note_0001: https://rubydoc.info/gems/elasticsearch-api
# note_0002: https://rubydoc.info/gems/elasticsearch-api/Elasticsearch/API/Cluster/Actions#health-instance_method
# note_0003: client.cluster.health から呼び出されるので実装が必要である
# note_0004: 'active_support' を 'active_support/core_ext' に変更する.
#            APIドキュメントにある 'active_support' 指定だと次のエラーが発生してしまうためである.
#            tutorial.rb:26:in `path_with_params': undefined method `blank?' for {}:Hash (NoMethodError)
# note_0005: require 'active_support' が存在しないと次のエラーが発生してしまう.
#            /usr/local/bundle/gems/activesupport-6.0.4/lib/active_support/core_ext/object/json.rb:42:
#              in `to_json': uninitialized constant ActiveSupport::JSON (NameError)
# note_0006: mapping は次の通り
# {"shakespeare"=>
#   {"mappings"=>
#     {"properties"=>
#       {"line_id"=>{"type"=>"long"},
#        "line_number"=>
#         {"type"=>"text",
#          "fields"=>{"keyword"=>{"type"=>"keyword", "ignore_above"=>256}}},
#        "play_name"=>
#         {"type"=>"text",
#          "fields"=>{"keyword"=>{"type"=>"keyword", "ignore_above"=>256}}},
#        "speaker"=>
#         {"type"=>"text",
#          "fields"=>{"keyword"=>{"type"=>"keyword", "ignore_above"=>256}}},
#        "speech_number"=>
#         {"type"=>"text",
#          "fields"=>{"keyword"=>{"type"=>"keyword", "ignore_above"=>256}}},
#        "text_entry"=>
#         {"type"=>"text",
#          "fields"=>{"keyword"=>{"type"=>"keyword", "ignore_above"=>256}}},
#        "type"=>
#         {"type"=>"text",
#          "fields"=>{"keyword"=>{"type"=>"keyword", "ignore_above"=>256}}}}}}}

結局

{"took"=>1,
 "timed_out"=>false,
 "_shards"=>{"total"=>1, "successful"=>1, "skipped"=>0, "failed"=>0},
 "hits"=>
  {"total"=>{"value"=>36, "relation"=>"eq"},
   "max_score"=>18.431282,
   "hits"=>
    [{"_index"=>"shakespeare",
      "_type"=>"_doc",
      "_id"=>"2633",

     {"_index"=>"shakespeare",
      "_type"=>"_doc",
      "_id"=>"27743",
      "_score"=>18.431282,
      "_source"=>
       {"type"=>"act",
        "line_id"=>27744,
        "play_name"=>"Coriolanus",
        "speech_number"=>7,
        "line_number"=>"",
        "speaker"=>"AUFIDIUS",
        "text_entry"=>"ACT V"}},
     {"_index"=>"shakespeare",
      "_type"=>"_doc",
      "_id"=>"31443",
      "_score"=>18.431282,
      "_source"=>
       {"type"=>"act",
        "line_id"=>31444,
        "play_name"=>"Cymbeline",
        "speech_number"=>13,
        "line_number"=>"",
        "speaker"=>"BELARIUS",
        "text_entry"=>"ACT V"}}]}}

验证

DevTool和Ruby的结果是否一致?

?看来大家的想法是一致的

image.png