简体   繁体   English

通过 Searchkick 按 integer 值对 Elasticsearch 结果进行排序

[英]Sort Elasticsearch results by integer value via Searchkick

I'm working on a Rails application that uses Searchkick as an interface to Elasticsearch.我正在开发一个使用 Searchkick 作为 Elasticsearch 接口的 Rails 应用程序。 Site search is working just fine, but I'm running into an unexpected issue on a page where I'm attempting to retrieve the most recent recoreds from Searchkick across a couple different models.站点搜索工作得很好,但是我在尝试从 Searchkick 跨几个不同模型检索最新记录的页面上遇到了一个意外问题。 The goal is a reverse chronological list of this recent activity, with the two object types intermingled.目标是最近活动的反向时间列表,两个 object 类型混合在一起。

I'm using the following code:我正在使用以下代码:

models = [ Post, Project ]
includes = { 
    Post    => [ :account => [ :profile ] ], 
    Project => [ :account => [ :profile ] ],
}
@results = Searchkick.search('*', 
    :models => models,
    :model_includes => includes,
    :order => { :id => :desc },
    :limit => 27,
)

For the purposes of getting the backend working, the page in development is currently just displaying the title, record type (class name), and ID, like this:为了让后端正常工作,开发中的页面目前只显示标题、记录类型(类名)和 ID,如下所示:

<%= "#{result.title} (#{result.class} #{result.id})" %>

Which will output this:其中将 output 这个:

Greetings from Tennessee! (Post 999)

This generally seems to be working fine, except that ES is returning the results sorted by ID as strings, not integers.这通常似乎工作正常,除了 ES 将按 ID 排序的结果返回为字符串,而不是整数。 I tested by setting the results limit to 1000 and found that with tables containing ~7,000 records, 999 is considered highest, while 6905 comes after 691 in the list.我通过将结果限制设置为 1000 进行测试,发现对于包含约 7,000 条记录的表,999 被认为是最高的,而 6905 在列表中排在 691 之后。

Looking through the Elasticsearch documentation, I do see mention of sorting numeric fields but I'm unable to figure out how to translate that to the Seachkick DSL.浏览 Elasticsearch 文档,我确实看到了对数字字段进行排序的提及,但我无法弄清楚如何将其转换为 Seachkick DSL。 It this possible and supported?这可能和支持吗?

I'm running Searchkick 4.4 and Elasticsearch 7.我正在运行 Searchkick 4.4 和 Elasticsearch 7。

Because Elasticsearch stores IDs as strings rather than integers, I solved this problem by adding a new obj_id field in ES and ordering results based on that.因为 Elasticsearch 将 ID 存储为字符串而不是整数,所以我通过在 ES 中添加一个新的obj_id字段并基于它对结果进行排序来解决这个问题。

In my Post and Project models:在我的 Post 和 Project 模型中:

def search_data
    {
        :obj_id => id,
        :title => title,
        :content => ActionController::Base.helpers.strip_tags(content),
    }
end

And in the controller I changed the order value to:在 controller 中,我将order值更改为:

:order => { :obj_id => :desc }

The records are sorting correctly now.记录现在正确排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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