ElasticSearch&累。搜索具有嵌套属性的对象

时间:2012-12-29 14:22:12

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

我花了几个小时试图解决问题。我希望有人可以帮助我。

首先,这里有一些代码来说明结构:

class Company < ActiveRecord::Base
  include Tire::Model::Search
  include Tire::Model::Callbacks

  attr_accessible :name, :website, :addresses_attributes

  has_many :addresses, dependent: :destroy
  accepts_nested_attributes_for :addresses, allow_destroy: true

  after_touch() { tire.update_index }

  include_root_in_json = false

  mapping do
    indexes :name, boost: 10
    indexes :addresses do
      indexes :street
    end
  end

  def self.search(params)
    s = tire.search(load: true) do

    query do
      boolean do
        must { string params[:query] } if params[:query]
        must { term "addresses.street", params[:location] } if params[:location]
      end
    end

    s.results
  end

  def to_indexed_json
    to_json( include: { addresses: { only: [:street] } } )
  end
end


class Address < ActiveRecord::Base
  # Attributes
  attr_accessible :street

  # Associations
  belongs_to :company, touch: true
end

当我尝试搜索具有特定街道名称的公司时(致电Company.search({location: 'example_street_name', query: 'example_name'})我没有结果。

索引对我来说很好看。这是其中一项要求:

curl -X POST "http://localhost:9200/companies/company/1351" -d '{
  "created_at": "2012-12-29T13:41:17Z",
  "name": "test name",
  "updated_at": "2012-12-29T13:41:17Z",
  "website": "text.website.com",
  "addresses": [
    {
      "street": "test street name"
    }
  ]
}'

我已经尝试了很多东西来获得结果。没有任何效果。看来我一定错过了一些基本的东西。

1 个答案:

答案 0 :(得分:2)

您正在对“addresses.street”字段使用term查询,该字段未进行分析,因此您必须传入较小的等值。

尝试使用match查询。