项目我使用Python..now用户可以给我一个关键词,我需要找到具有这些关键字的文章writitng的文章,其内容和关键字MongoDB数据库..Pymongo和DB
我wrting到如下DB:
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)
关键字是bnary元组
[("africa",3),("content",5),...]
我想知道锄实现上述usecases..I列表neeed到travese在数据库中的所有记录找条公顷ving一个特定的关键字
写下面这个uery?
def getArticlesbyKeywords(self,keyword,showBody=False):
client = pymongo.MongoClient(
"mongodb://mahdi:[email protected]: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
在我蒙戈DB的样本记录如下:
Keywords: "[{'count': 20, 'key': 'north'}, {'count': 13, 'key': 'image'}, {'count': 13, 'key': 'korean'}, {'count': 10, 'key': 'malaysian'}, {'count': 9, 'key': 'kim'}]"
嗨,谢谢你的回答,当我得到我的结果时,我可以根据更高的分数对它进行排序吗? – Mehdi
是的,按“$ meta”排序:“textScore”。我已经更新了我的答案。 –
嗨,我使用你的代码时,我得到了异常,我编辑了我的问题上面。 – Mehdi