简体   繁体   中英

Sorting by number of nested elements with ElasticSearch and Tire

Given the following mapping on a model called Post, is it possible to build a query that returns posts ordered by the number of votes cast within a specific time range (eg. past 7 days)?

mapping do
   indexes :id, type: 'integer'
   indexes :user_id, type: 'integer'
   indexes :name, boost: 10
   indexes :body # analyzer: 'snowball'
   indexes :created_at, type: 'date'
   indexes :vote_count, type: 'integer'

   indexes :topic_ids

   indexes :topics do
       indexes :id, type: 'integer'
       indexes :name, type: 'string'
    end

   indexes :votes do
       indexes :user_id, type: 'integer'
       indexes :created_at, type: 'date'
   end
end

I'm using Tire in Rails 3.2.13. I have a Post model and a Vote model. A Post has many votes, and a Vote belongs to Post.

Yes, you can either sort on the vote_count atrribute, or use the custom_score query for fine-grained relevancy computation.

For the former, something like:

require 'tire'

s = Tire.search do
  query do
    filtered do
      query { all }
      filter :range, 'created_at' => { from: '-7d' }
    end
  end
  sort do
    by :vote_count
  end
end

puts s.to_curl

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