首页 > 解决方案 > API Get 方法以 JSON 格式获取主题标签计数大于 MongoDB 中的所有推文

问题描述

我有一个 MongoDB 数据库,其中包含许多推文。我希望能够通过我的 API 获取 JSON 列表中的所有推文,这些推文包含的主题标签数量大于用户在 url 中指定的主题标签(例如http://localhost:5000/tweets?morethan=5,即5 在这种情况下)。

主题标签包含在数据库中的实体列中,以及其他列,例如 user_mentions、urls、symbols 和 media。这是我到目前为止编写的代码,但没有返回任何内容。

#!flask/bin/python

app = Flask(__name__)

@app.route('/tweets', methods=['GET'])
def get_tweets():
# Connect to database and pull back collections

db = client['mongo']
collection = db['collection']

parameter = request.args.get('morethan')

if parameter:
    gt_parameter = int(parameter) + 1  # question said greater than not greater or equal
    key_im_looking_for = "entities.hashtags.{}".format(gt_parameter)  # create the namespace#
    cursor = collection.find({key_im_looking_for: {"$exists": True}})

编辑:它有效!

标签: pythonmongodbmongodb-querypymongo

解决方案


有问题的代码是这一行

cursor = collection.find({"entities": {"hashtags": parameter}})

这个答案解释了为什么不可能直接执行你的要求。

mongodb 查询:$size 和 $gt 总是返回 0

该答案还描述了绕过它的潜在(但糟糕的)想法。

最好的建议是修改所有文档并将“num_hashtags”键放在某处,对其进行索引并对其进行查询。

使用Twitter JSON API,您可以更新所有文档并将 num_hashtags 键放入实体文档中。

或者,您可以通过对所有文档进行非常慢的全表扫描来解决您的直接问题,以通过滥用MongoDB Dot Notation检查是否存在比您的参数大一的标签编号。

gt_parameter = int(parameter) + 1  # question said greater than not greater or equal
key_im_looking_for = "entities.hashtags.{}".format(gt_parameter)  #create the namespace# 
# py2.7 => key_im_looking_for = "entities.hashtags.%s" %(gt_parameter) 
# in this example it would be "entities.hashtags.6"
cursor = collection.find({key_im_looking_for: {"$exists": True}})

最好的答案(也是首先使用 NoSQL 数据库的关键原因)是您应该修改数据以适应您的检索。如果可能,您应该执行添加 num_hashtags 键的就地更新。


推荐阅读