快速上手pymongo

在上手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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,992評論 19 139
  • Scrapy,Python開發的一個快速,高層次的屏幕抓取和web抓取框架,用于抓取web站點并從頁面中提取結構化...
    Evtion閱讀 5,915評論 12 18
  • python程序員提高必做開源項目robobrowser A library for web scraping b...
    Python程序媛閱讀 12,347評論 7 146
  • 聚焦在 Twitter 上關于Apache Spark的數據,目標是準備將來用于機器學習和流式處理應用的數據。 ...
    abel_cao閱讀 2,714評論 1 12
  • 車站的座椅面對面,你看看我,我看看你,脫落的痕跡是歲月的印記。 車站的座椅迎來送往,等待與期盼,離別與不舍,都彌漫...
    時間下的一場雨閱讀 257評論 0 0