Mongodb Pymongo和数据库中的项目
我正在写一篇文章,它的内容和关键字都使用Python写入MongoDB数据库。现在用户可以给我一个关键字,我需要找到包含这些关键字的文章 我向DB写信如下:Mongodb Pymongo和数据库中的项目,mongodb,python-2.7,pymongo,Mongodb,Python 2.7,Pymongo,我正在写一篇文章,它的内容和关键字都使用Python写入MongoDB数据库。现在用户可以给我一个关键字,我需要找到包含这些关键字的文章 我向DB写信如下: myrecord = {"Link": link, "Title": title, "HeadLine": headline, "BodyText":innerBodyText, "Keywords":keywords,
myrecord = {"Link": link,
"Title": title,
"HeadLine": headline,
"BodyText":innerBodyText,
"Keywords":keywords,
"date": datetime.datetime.utcnow()
}
try:
print("Inserting the record in the DB")
result = my_collection.insert_one(myrecord, False)
关键字是B元元组的列表
[("africa",3),("content",5),...]
我想知道如何实现上述用例。我需要遍历数据库中的所有记录,以查找具有特定关键字的文章
写在下面是为了这个
def getArticlesbyKeywords(self,keyword,showBody=False):
client = pymongo.MongoClient(
"mongodb://mahdi:Isentia@aws-ap-southeast-1-portal.2.dblayer.com:15312,aws-ap-southeast-1-portal.0.dblayer.com:15312/BBCArticles?ssl=true",
ssl_cert_reqs=ssl.CERT_NONE)
mydb = client['BBCArticles']
my_collection = mydb['Articles']
my_collection.create_index([("Keywords.key", "text")])
print 'Articles containing higher occurences of the keyword is sorted as follow:'
for doc in my_collection.find({"$text": {"$search": keyword}}).sort({"score": {"$meta": "textScore"}}):
print(doc))
我得到以下错误:
Traceback (most recent call last):
File "api_access.py", line 21, in <module>
api.getArticlesbyKeywords("BBC")
File "api_access.py", line 15, in getArticlesbyKeywords
for doc in my_collection.find({"$text": {"$search": keyword}}).sort({"score": {"$meta": "textScore"}}):
File "C:\Python27\lib\site-packages\pymongo\cursor.py", line 660, in sort
keys = helpers._index_list(key_or_list, direction)
File "C:\Python27\lib\site-packages\pymongo\helpers.py", line 63, in _index_list
raise TypeError("if no direction is specified, "
TypeError: if no direction is specified, key_or_list must be an instance of list
为了使此数据可查询,您需要一个稍微不同的模式。插入文档数组而不是成对数组:
my_collection.insert_one({
"Keywords": [{"key": "africa", "score": 3},
{"key": "content", "score": 5}]
})
然后您可以进行如下查询:
for doc in my_collection.find({"Keywords.key": "africa"}):
print(doc)
确保创建索引:
my_collection.create_index([("Keywords.key", 1)])
如果需要更复杂的查询,请使用文本索引:
my_collection.create_index([("Keywords.key", "text")])
for doc in my_collection.find(
{"$text": {"$search": "africa"}}
).sort({"score": {"$meta": "textScore"}}):
print(doc)
请参阅和。使用$elemMatch在数组中搜索
db.test1.find({"items":{"$elemMatch" : {"$elemMatch": {"$in": ["a"]}}}})
{ "_id" : ObjectId("58a9a9805cfd72c8efd8f315"), "name" : "a", "items" : [ [ "a", 1 ], [ "b", 2 ] ] }
为什么不像这样使用子文档呢
关键词:[{
kw:“非洲”,
计数:3
},…]
然后你可以用鸟巢。比如{“keywords.kw”:“africa”}要搜索。您好,谢谢您的回答,当我得到结果时,我能按高分排序吗?是的,按“$meta”:“textScore”排序。我已经更新了我的答案。嗨,当我使用你的代码时,我遇到了异常,我已经编辑了上面的问题。我怀疑你使用的是过时的PyMongo。什么是“pymongo.version”?
db.test1.find({"items":{"$elemMatch" : {"$elemMatch": {"$in": ["a"]}}}})
{ "_id" : ObjectId("58a9a9805cfd72c8efd8f315"), "name" : "a", "items" : [ [ "a", 1 ], [ "b", 2 ] ] }