Elasticsearch和后续的Mongodb查询 [英] Elasticsearch and subsequent Mongodb queries

查看:190
本文介绍了Elasticsearch和后续的Mongodb查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Elasticsearch实现搜索功能.

I am implementing search functionality using Elasticsearch.

我收到了Elasticsearch返回的用户名"集,之后我需要查询MongoDB中的集合以获取用户名"集中每个用户的最新评论.

I receive "username" set returned by Elasticsearch after which I need to query a collection in MongoDB for latest comment of each user in the "username" set.

问题:可以说,每次查询Elasticsearch时,我都会收到约100个用户名,这是查询MongoDB以获得每个用户最新评论的最快方法.使用.findOne()在for循环中查询MongoDB 100次是唯一的选择吗?

Question: Lets say I receive ~100 usernames everytime I query Elasticsearch what would be the fastest way to query MongoDB to get the latest comment of each user. Is querying MongoDB 100 times in a for loop using .findOne() the only option?

(注意-因为用户的最新评论经常更改,所以我不想将其存储在Elasticsearch中,因为这将触发整个文档的检索-更改-重新索引过程太频繁了)

(Note - Because latest comment of a user changes very often, I dont want to store it in Elasticsearch as that will trigger retrieve-change-reindex process for the entire document far too frequently)

推荐答案

此答案假定存储在comments数据库中的mongo数据库具有以下架构.

This answer assumes following schema for your mongo db stored in comments db.

{
  "_id" : ObjectId("5788b71180036a1613ac0e34"),
  "username": "abc",
  "comment": "Best"
}

假设usernames是您从elasticsearch获得的用户列表,则可以执行以下aggregate:

assuming usernames is the list of users you get from elasticsearch, you can perform following aggregate:

a =[
    {$match: {"username":{'$in':usernames}}},
    {$sort:{_id:-1}},
    {
       $group:
         {
           _id: "$username",
           latestcomment: { $first: "$comment" }
         }
     }
]
db.comments.aggregate(a)

这篇关于Elasticsearch和后续的Mongodb查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆