2017-02-19 42 views
0

项目我使用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'}]" 

回答

1

你需要一个稍微不同的模式,以使该数据可查询。插入的文件的数组,而不是对的数组:

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) 

MongoDB Text Indexessort by meta

+0

嗨,谢谢你的回答,当我得到我的结果时,我可以根据更高的分数对它进行排序吗? – Mehdi

+0

是的,按“$ meta”排序:“textScore”。我已经更新了我的答案。 –

+0

嗨,我使用你的代码时,我得到了异常,我编辑了我的问题上面。 – Mehdi

0

使用$ elemMatch在数组中搜索。

db.test1.find({"items":{"$elemMatch" : {"$elemMatch": {"$in": ["a"]}}}}) 
{ "_id" : ObjectId("58a9a9805cfd72c8efd8f315"), "name" : "a", "items" : [ [ "a", 1 ], [ "b", 2 ] ] } 

为什么不使用子文档一样

关键字:[{ 千瓦: “非洲”, 数:3 },...]

那么你可以使用嵌套。如{“keywords.kw”:“africa”}来搜索。