简体   繁体   English

Pymongo全文中文搜索

[英]Pymongo full text search in chinese

I know Pymongo supports text search feature for many languages eg English, French, German..., but it doesn't work for Chinese. 我知道Pymongo支持多种语言的文本搜索功能,例如英语,法语,德语...,但不适用于中文。 Is there a available way to implement Chinese full text search, under the environment of MongoDB 3.4 + Pymongo 3.4 ? 在MongoDB 3.4 + Pymongo 3.4的环境下,是否有可用的方法来实现中文全文搜索?

I think the main reason that pymongo free version doesn't support Chinese full text search is that Chinese segmentation is difficult. 我认为pymongo免费版不支持中文全文搜索的主要原因是很难进行中文分割。 I have an indirect approach to tackle Chinese full text search by Pymongo. 我有一个间接的方法来处理Pymongo的中文全文搜索。 One can finish the segmentation before he store the corpus into MongoDB or search a sentence from MongoDB. 在将语料库存储到MongoDB或从MongoDB中搜索句子之前,可以先完成细分。 The jieba module is what I strongly recommends for Chinese segmentation. 我强烈建议对jieba模块进行中文细分。 There is a self-contained simple example, which works for me to some extent. 有一个独立的简单示例,在某种程度上对我有用。

from pymongo import MongoClient
from pymongo import TEXT
import jieba
client = MongoClient()
dialogs = client['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'})]):
    print(x)

OUTPUT: OUTPUT:

keywords: 你 今天 早上 去 哪 了 ?
{'_id': ObjectId('59673a0d5975ae05e9b27dd8'), 'text_in': '你 今天 准备 去 哪 ?', 'text_out': '我 要 回家', 'score': 2.4}
{'_id': ObjectId('59673a0d5975ae05e9b27dd7'), 'text_in': '你 早上 吃 的 什么 ?', 'text_out': '我 吃 的 鸡蛋', 'score': 1.2}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM