python - 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}})
编辑:它有效!
解决方案
有问题的代码是这一行
cursor = collection.find({"entities": {"hashtags": parameter}})
这个答案解释了为什么不可能直接执行你的要求。
该答案还描述了绕过它的潜在(但糟糕的)想法。
最好的建议是修改所有文档并将“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 键的就地更新。
推荐阅读
- android - 使用 ListAdapter 更新 recyclerview 中的一行
- angular - 没有 SyncFusion 角度调度器的样式
- javascript - Javascript:: 更改单选按钮上的 addEventListener 无法使用 requirejs
- python - 如何在不获取 W504 的情况下修复“二元运算符之前的 W503 换行符”?
- javascript - 在 React 中使用多行 javascript
- python - 如何在 Django 中获取 python 文件数据?
- swiftui - SwiftUI:不同视图之间的数据共享
- heroku - 我构建了heroku应用程序并且我构建成功但是Dynos无法显示我的代码当然我等待了很多
- node.js - 如何在 Firebase Cloud 中托管具有 PeerJS 依赖项的 NodeJS 应用程序?
- java - Jacoco 显示行没有被覆盖,即使 IntelliJIdea 静态代码分析器说它们被覆盖