简体   繁体   中英

ElasticSearch & Tire. Search for an object with nested attributes

I've spent several hours trying to solve the problem. I hope someone can help me.

First, here's some code to illustrate the structure:

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

When I'm trying to search for company with particular street name (calling Company.search({location: 'example_street_name', query: 'example_name'}) I get no results.

Indexing looks fine for me. That's one of the requests:

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"
    }
  ]
}'

I've tried many things to get the results. Nothing worked. It seems I must have missed something basic.

You're using a term query for the "addresses.street" field, which is not analyzed, so you must pass in lowercased etc. values.

Try using the match query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM