在上手pymongo之前
pymongo是python調用MongoDB的一個driver, 那么在使用pymongo之前, 要保證你已經做到以下兩點:
- 安裝好mongo
- 啟動mongo
安裝和啟動的流程網上很容易找到.
本文mongo使用默認的ip和port, 即localhost和27017, 這個課根據需要自己修改.
準備工作
導入必要的python模塊, jieba是用于中文分詞的module, pprint能打印出格式整潔的輸出.
import pymongo
from pymongo import MongoClient # MongoClient是必須的
from pymongo import TEXT # 全文索引時會用到
import jieba # 中文分詞工具,下面的例子會用到
import pprint # pretty print 工具包, 用這個打印格式更整潔
先定義兩個簡單的條目, 后面的插入和查找會用到. 這種定義方式就是json嘛, 很直觀.
item1 = {
'name': "Burger",
'ingredients': [
"bread",
"cheese",
"tomato",
"beef"
]
}
item2 = {
'name': 'Pizza',
'ingredients': [
'cheese',
'bacon',
'flour',
'pepper'
]
}
插入一個條目
# 初始化一個client實例
client = MongoClient()
# 建立或者調用一個名為recipe的database
db = client['recipe']
# 建立或調用一個名為posts的collection
foods = db['foods']
# 把item1條目插入到foods
foods.insert_one(item1)
列出數據庫db下的所用的collection的名稱
db.collection_names(include_system_collections=False)
隨機找出foods中的一個條目(也就是一個document)
db.foods.find_one()
插入一個新的條目, 并打印出collection中所有的document(這里collection就是foods, foods的documents就是item1和item2)
foods.insert_one(item2)
pprint.pprint([x for x in foods.find({'ingredients': 'cheese'})])
OUTPUT:
[{'_id': ObjectId('5967807e5975ae05e9b27dfe'),
'ingredients': ['bread', 'cheese', 'tomato', 'beef'],
'name': 'Burger'},
{'_id': ObjectId('5967807e5975ae05e9b27dff'),
'ingredients': ['cheese', 'bacon', 'flour', 'pepper'],
'name': 'Pizza'}]
英文全文搜索(full text search)用例
下面這段程序可以用于全文搜索, 倒數第二行代碼可以得出輸入語句于數據庫每個條目的text_in
字段的相似度分數. 對于英語mongo直接支持full text search, 不用人為分詞等操作.
dialogs = db['dialogs']
d1 = {
'text_in': 'this ball and this ball are toys in the house',
'text_out': 'find thank you',
'keywords_dialog': ['ball', 'toys', 'house'],
}
d2 = {
'text_in': 'this ball is a toys in the house this is a car and a space boat computer is a hammer',
'text_out': 'i am 9',
'keywords_dialog': ['ball', 'toys', 'car'],
}
dialogs.insert_many([d1,d2])
dialogs.create_index([('text_in', TEXT)], default_language='en')
keywords = 'ball toys'
cursor = dialogs.find({'$text': {'$search':keywords}}, {'score':{'$meta':'textScore'}})
pprint.pprint([x for x in cursor])
OUTPUT:
[{'_id': ObjectId('5967807e5975ae05e9b27e01'),
'keywords_dialog': ['ball', 'toys', 'car'],
'score': 1.125,
'text_in': 'this ball is a toys in the house this is a car and a space boat '
'computer is a hammer',
'text_out': 'i am 9'},
{'_id': ObjectId('5967807e5975ae05e9b27e00'),
'keywords_dialog': ['ball', 'toys', 'house'],
'score': 1.75,
'text_in': 'this ball and this ball are toys in the house',
'text_out': 'find thank you'}]
中文全文檢索
MongoDB是不支持中文的full text search的(好像付費企業版支持), 我發現如果提前分好詞, 在英文模式下也是可以用的.
注意這段代碼的倒數第二行cursor.sort([('score', {'$meta':'textScore'})])
, 能根據搜索的相似度排序, 很方便.
dialogs = db['dialogs_zh_fulltext']
d1 = {
'text_in': '你 早上 吃 的 什么 ?',
'text_out': '我 吃 的 雞蛋',
}
d2 = {
'text_in': '你 今天 準備 去 哪 ?',
'text_out': '我 要 回家',
}
dialogs.insert_many([d1,d2])
dialogs.create_index([('text_in', TEXT)], default_language='en')
keywords = ' '.join(jieba.lcut('你今天早上去哪了?'))
print('keywords: {}'.format(keywords))
cursor = dialogs.find({'$text': {'$search':keywords}}, {'score':{'$meta':'textScore'}})
for x in cursor.sort([('score', {'$meta':'textScore'})]):
pprint.pprint(x)
OUTPUT:
keywords: 你 今天 早上 去 哪 了 ?
{'_id': ObjectId('5967807e5975ae05e9b27e05'),
'score': 2.4,
'text_in': '你 今天 準備 去 哪 ?',
'text_out': '我 要 回家'}
{'_id': ObjectId('5967807e5975ae05e9b27e04'),
'score': 1.2,
'text_in': '你 早上 吃 的 什么 ?',
'text_out': '我 吃 的 雞蛋'}
參考鏈接:
http://api.mongodb.com/python/current/tutorial.html
http://api.mongodb.com/python/current/api/pymongo/collection.html
http://www.runoob.com/mongodb/mongodb-text-search.html