【问题标题】:Tire gem: How to access Elasticsearch's 'highlight' property?轮胎宝石:如何访问 Elasticsearch 的“高亮”属性?
【发布时间】:2013-01-17 22:19:03
【问题描述】:

我有一些在 Elasticsearch 中被索引的 Rails 模型(通过 Tire gem)。我可以索引新文档并查询现有索引。

我似乎无法从我的 Rails 应用程序中获取附加到记录的 highlight。但是,我可以看到,当我通过curl 直接与 Elasticsearch 交互时,json 中返回了highlight

当我尝试访问我的记录的 highlight 属性时,我得到:undefined method 'highlight' for #<Report:0x007fe8afa54700>

# app/views/reports/index.html.haml
%h1 Listing reports
...
  - @reports.results.each do |report|
    %tr
      %td= report.title
      %td= raw report.highlight.attachment.first.to_s

但是如果我使用curl,我可以看到highlight 被返回到了Tire...

$ curl -X GET "http://localhost:9200/testapp_development_reports/report/_search?load=true&pretty=true" -d '{query":{"query_string":{"query":"contains","default_operator":"AND"}},"highlight":{"fields":{"attachment":{}}}}'
{
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "failed" : 0
  },
  "hits" : {
    "total" : 2,
    "max_score" : 0.111475274,
    "hits" : [ {
      "_index" : "testapp_development_reports",
      "_type" : "report",
      "_id" : "1",
      "_score" : 0.111475274, "_source" : {"id":1,"title":"Sample Number One",...,"attachment":"JVBERi0xMJ1Ci... ...UlRU9GCg==\n"},
      "highlight" : {
        "attachment" : [ "\nThis <em>contains</em> one\n\nodd\n\n\n" ]
      }
    }, {
      "_index" : "testapp_development_reports",
      "_type" : "report",
      "_id" : "2",
      "_score" : 0.111475274, "_source" : {"id":2,"title":"Number two",...,"attachment":"JVBERi0xLKM3OA... ...olJVPRgo=\n"},
      "highlight" : {
        "attachment" : [ "\nThis <em>contains</em> two\n\neven\n\n\n" ]
      }
    } ]
  }
}

模型中的搜索方式:

  ...
  def self.search(params)
    tire.search(load: true) do
      query { string params[:query], default_operator: "AND" } if params[:query].present?
      highlight :attachment
    end
  end
  ...

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 elasticsearch tire


    【解决方案1】:

    当您使用load: true 选项时,方法highlight 是不可访问的。这应该会在未来的轮胎版本中得到修复。

    编辑:您现在可以使用each_with_hit 方法访问返回的elasticsearch 值

    例如:

    results = Article.search 'One', :load => true
      results.each_with_hit do |result, hit|
      puts "#{result.title} (score: #{hit['_score']})"
    end
    

    【讨论】:

    • 您知道何时以及如何修复它(直接访问@response['hits']['hits'])吗?因为我在问题中没有找到任何关于它的信息。
    【解决方案2】:

    你可以在这篇文章中找到我的答案 Elasticsearch/Lucene highlight

    我的方法对我来说很好,希望你也能得到它。

    【讨论】:

      猜你喜欢
      • 2012-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-04
      • 2012-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多