【问题标题】:How to fetch a document by its ID in elasticsearch rails如何在elasticsearch rails中通过其ID获取文档
【发布时间】:2015-08-25 00:38:49
【问题描述】:

我在 elasticsearch 文档中看到您可以通过其 ID 获取文档。 elasticsearch rails有什么等价物吗?我通过 API 提供“as_indexed_json”,这是一个有点昂贵的查询,我想在我的 API 中直接从 elasticsearch 返回 ths JSON。

【问题讨论】:

    标签: elasticsearch elasticsearch-rails


    【解决方案1】:

    您可以使用Elasticsearch::Transport::Client 上的get 方法按id 从给定索引中获取特定文档。 get 方法需要一个哈希参数,其中包含要从中获取的索引的键和要获取的文档的 id。

    所以,你需要三样东西:

    1. 客户端对象
    2. 索引名称
    3. 文档的 ID(即您的模型 ID)
    client = YourModel.__elasticsearch__.client
    document = client.get({ index: YourModel.index_name, id: id_to_find })
    

    【讨论】:

      【解决方案2】:

      您可以在这里完成它。 这是来自控制器操作,对我来说效果很好。

      def show
        client = Elasticsearch::Client.new host:'127.0.0.1:9200', log: true
        response = client.search index: 'example', body: {query: { match: {_id: params[:id]} } }
        @example = response['hits']['hits'][0]['_source']
         respond_to do |format|
           format.html # show.html.erb
           format.js # show.js.erb
           format.json { render json: @example }
         end
        @records = Example.search(@example['name']).per(12).results
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-03
        • 1970-01-01
        • 1970-01-01
        • 2019-12-11
        相关资源
        最近更新 更多