【问题标题】:Advanced search with gem Tire and elasticsearch使用 gem Tire 和 elasticsearch 进行高级搜索
【发布时间】:2012-06-10 19:05:38
【问题描述】:

我正在尝试使用 gem 轮胎在我的应用程序中进行搜索。我有表格区域、城市、酒店、房间和房间信息。

我需要的是通过查询和其他文本字段(如 date_from、date_to 和房间数)查找酒店。 在模型中,我有计算酒店是否有空闲房间并发送布尔值的方法。 如何使用此布尔方法过滤查询?

谢谢

在hotel.html.erb中

<%= form_tag search_hotels_path, :method => 'post' do %>
  <%= label_tag :query %>
  <%= text_field_tag :query, params[:query] %>
  <%= label_tag 'From' %>
  <%= text_field_tag :date_f, params[:date_from] %>
  <%= label_tag 'To' %>
  <%= text_field_tag :date_to, params[:date_to] %>
  <%= label_tag 'Rooms' %>
  <%= text_field_tag :rooms, params[:rooms] %>
  <%= submit_tag :search %>
<% end %>

在酒店.rb

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

belongs_to :city
belongs_to :area
has_one :area, :through => :city
has_many :rooms, :dependent => :delete_all


def search(params)

        tire.search do
            query do
                boolean do  
                    must { string params[:query] } if params[:query].present?
                    must { term rooms_available params, true}
                end
            end 
        end

end

self.include_root_in_json = false
def to_indexed_json
    to_json(methods: [:area_name,:city_name])
end

def area_name
    city.area.name
end
def city_name
    city.name
end


def rooms_available params
    exit
    begin_date = params[:date_from].to_date
    end_date = params[:date_to].to_date
    number_of_rooms = params[:rooms]

    rooms.each do |room|
        if room.available(begin_date, end_date, number_of_rooms)
            return true
        end
    end
    return false
end

end

【问题讨论】:

  • Elasticsearch 首先是一个搜索引擎。它的表连接机制极差。要实现您想要的,您必须将数据库反规范化为最多两个表:(Areas, Cities, Hotels) -> Hotels 和 (Rooms and RoomInformations) -> Rooms,然后使用 Has Child 查询 (@987654321 @)。但是,我认为切换到关系数据库可能会更好。

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


【解决方案1】:

把这个放到 to_json 方法中:

def to_json
  {
    :area_name => self.area_name, 
    :city_name => self.city_name,
    :rooms_available => self.rooms_available
   }.to_json
end

然后:

def search(params)

    tire.search do
        query do
            boolean do  
                must { string params[:query] } if params[:query].present?
                must { term rooms_available, true}
            end
        end 
    end

end

不过,在这种情况下,最好将 rooms_available 放在过滤器中,因为这是必须的,而且您并不关心对该子句的评分。

def search(params)

    tire.search do
        query do
            boolean do  
                must { string params[:query] } if params[:query].present?
            end
        end 
        filter do
            boolean do  
               must { term rooms_available, true}
            end
        end
    end

end

希望这会有所帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-03
    • 2012-04-21
    • 1970-01-01
    • 1970-01-01
    • 2012-05-07
    • 2012-12-09
    • 1970-01-01
    相关资源
    最近更新 更多