Ruby on rails 基于searchkick中的两个唯一字段(与SQL DISTINCT相同)获取结果
我有一个Ruby on rails 基于searchkick中的两个唯一字段(与SQL DISTINCT相同)获取结果,ruby-on-rails,
elasticsearch,searchkick,Ruby On Rails,
elasticsearch,Searchkick,我有一个Follow模型,它(除其他外)有两个属性follower\u id和follower\u id 这是搜索数据定义: { name: [followable.name, follower.name], username: [followable.username, follower.username], followable_id: followable_id, follower_id: follower_id } 我想执行一个搜索,返回唯一的结果,考虑到字段[foll
Follow
模型,它(除其他外)有两个属性follower\u id
和follower\u id
这是搜索数据定义:
{
name: [followable.name, follower.name],
username: [followable.username, follower.username],
followable_id: followable_id,
follower_id: follower_id
}
我想执行一个搜索,返回唯一的结果,考虑到字段[followable\u id,follower\u id]。我认为这类似于选择DISTINCT ON followable\u id,follower\u id FROM“follows”
例如,[[10,2],[2,5],[2,10]]
应该返回[[10,2],[2,5]]
或[[2,5],[2,10]]
,对我来说,顺序没有区别。对我来说,重要的是这一对不再重复
以下是我当前的搜索结果:
search = Follow.search('*',
fields: [:name, :username],
match: :word_start,
misspellings: {below: 5},
page: params[:page],
per_page: 10,
where: {_or: [
{follower_id: current_user.id},
{followable_id: current_user.id}
]}
)
编辑:
我想我们可以相似。但是,我尝试了以下方法:
SELECT DISTINCT ON (follower_id, followable_id) follower_id, followable_id FROM "follows";
follower_id | followable_id
-------------+---------------
27 | 35
28 | 12
33 | 27
35 | 27
在本例中,它不应返回
[27,35]
或[35,27]
。但正如您所看到的,查询确实返回了重复的一对。我不知道searchkick,但我可以共享E.S等价物(如果有帮助的话),您可以将其转换为searchkick等价物
{
"size": 0,
"aggs": {
"distinct": {
"terms": {
"script": {
"source": "doc['follower_id'] + '|' + doc['followable_id']"
},
"size": 100
}
}
}
}
您好,Sahil,您使用size键的目的是什么?根级别的size用于查询结果,而使用in-aggregation的size用于聚合结果。如果这解决了你的问题,请接受答案并投票表决。谢谢,谢谢。我得到的结果是空的,这是我发送给ES的json:{“查询”:{“bool”:{“必须”:{“匹配所有”:{},“过滤器”:[{“bool”:{“应该”:[{“bool”:{“过滤器”:[{“术语”:[{“follower id”:2}}}}},{“bool”:{“过滤器”:[{“术语”:{“followable id”:2}}}}}}}}}}}}}}},{“超时”:“11s”,“{“源代码”:false,“源代码”:false,“大小”;{“follower id”:2}}}{“源代码”:+'|'+doc['followable_id'],“size:100}}}}这里是一个示例文档:{“_index”:“follows_staging_20200828101649804”,“_type”:“_doc”,“_id”:“1”,“_version”:1,“_seq_no”:0”,“_primary_term”:1,“found”:true”,“_source”:“{”name:[“user1”,“user2”,“user2”,“username”:“myuser1”,“myuser2”,“followable”;“follower id”