본문 바로가기
Programming/Ruby On Rails

[Ruby On Rails] Elasticsearch 검색 템플릿(Search Template) 사용하기

by 가론노미 2023. 3. 28.

2023.03.26 - [Programming/ElasticSearch] - [ElasticSearch] 검색 템플릿이란? (Search Template)

위 포스팅에서는 Elasticsearch의 검색 템플릿에 대해 정리하였다.

 

그러면 이 검색 템플릿을 Ruby On Rails 프로젝트에서는 어떻게 사용할 수 있을까?

Elasticsearch에서는 공식 Ruby 클라이언트를 제공하고 있는데 elasticsearch gem을 다운로드하여 두 개의 개별 라이브러리를 사용할 수 있다.

  • elastic-transport- Elasticsearch 클러스터에 연결하기 위한 저수준 코드를 제공
  • elasticsearch-api- Elasticsearch RESTful API를 위한 Ruby API를 제공

https://www.elastic.co/guide/en/elasticsearch/client/ruby-api/current/examples.html#ex-reindex

 

Examples | Elasticsearch Ruby Client [8.6] | Elastic

Below you can find examples of how to use the most frequently called APIs with the Ruby client. Indexing a documentedit Let’s index a document with the following fields: name, author, release_date, and page_count: body = { name: "The Hitchhiker's Guide t

www.elastic.co

문서에 인덱싱, 조회, 업데이트, 삭제 등 호출 가능한 API 예제들이 정리되었지만

검색 템플릿 관련해서 정리된 문서를 찾지 못해 해당 gem의 github 코드를 찾아보았다.

 

사용 가능한 api의 action들이 모여있는 듯한 폴더를 찾았고 그 중에 search_template.rb 파일을 확인해 보았다.

https://github.com/elastic/elasticsearch-ruby/blob/main/elasticsearch-api/lib/elasticsearch/api/actions/search_template.rb

def search_template(arguments = {})
    raise ArgumentError, "Required argument 'body' missing" unless arguments[:body]

    arguments = arguments.clone
    headers = arguments.delete(:headers) || {}

    body   = arguments.delete(:body)

    _index = arguments.delete(:index)

    method = Elasticsearch::API::HTTP_POST
    path   = if _index
               "#{Utils.__listify(_index)}/_search/template"
             else
               "_search/template"
             end
    params = Utils.process_params(arguments)

    Elasticsearch::API::Response.new(
      perform_request(method, path, params, body, headers)
    )
end

 

대충 코드를 봤을 때 다른 예제와 비슷하게 인수로 hearders와 body, index를 받고 있고 body는 필수값인 듯했다.

body를 그대로 넘겨 API를 호출하고 있으니 지난번 알아온 검색 쿼리와 동일하게 넘겨주면 검색 템플릿을 사용한 결과를 받을 수 있다.

body = {
    id: 'my-search-template',
    params: {
      query_string: 'hello world',
      from: 20,
      size: 10
    }
  }

client.search_template(index: 'my_index', body: body)