1、建立索引

#coding=utf-8
from __future__ import unicode_literals
__author__ = 'zh'
import sys,os
from whoosh.index import create_in,open_dir
from whoosh.fields import *
from jieba.analyse import ChineseAnalyzer
import pymongo
import json
from pymongo.collection import Collection
from pymongo import database class CreatIndex:
def __init__(self):
self.mongoClient = pymongo.MongoClient('192.168.229.128',27017)
self.websdb = pymongo.database.Database(self.mongoClient,'webdb')
self.pagesCollection = Collection(self.websdb,'pages')
def BuiltIndex(self):
analyzer = ChineseAnalyzer()
# 索引模版
schema = Schema(
U_id=ID(stored=True),
# md5=ID(stored=True),
title=TEXT(stored=True,analyzer=analyzer),
location=TEXT(stored=True),
publish_time=DATETIME(stored=True,sortable=True),
content=TEXT(stored=False,analyzer=analyzer)
)
from whoosh.filedb.filestore import FileStorage
storage = FileStorage("../whoosh_index")
if not os.path.exists("../whoosh_index"):
os.mkdir("../whoosh_index")
ix = storage.create_index(schema)
print '建立索引文件!'
else:
ix=storage.open_index() # if not os.path.exists("whoosh_index"):
# os.mkdir("whoosh_index")
# ix = create_in("whoosh_index", schema) # for create new index
# #ix = open_dir("tmp") # for read only
writer = ix.writer()
try:
num=0
while(True):
# break
try:
row=self.pagesCollection.find_one({'indexed':{'$exists':False}})
if row!=None:
publish_time=None
if row.has_key('publish_time'):
publish_time=row['publish_time']
if str(publish_time)=='' or str(publish_time)=='':
publish_time=None
location=''
if row.has_key('location'):
location=json.JSONEncoder().encode(row['location']) writer.add_document(
U_id=''.join(str(row['_id'])),
# md5=row['md5'],
title=row['name'],
location=''.join(location),
publish_time=publish_time,
content=row['information']
)
self.pagesCollection.update_one({"_id":row["_id"]},{"$set":{"indexed":True}})
num+=1
print row["_id"],"已建立索引!"
else:
writer.commit()
print "全部处理完毕"
# time.sleep(3600)
# self.BuiltIndex()
break
except:
print row["_id"],"异常"
break
except:
writer.commit()
print "异常"
# print '已处理',num,'共计', self.pagesCollection.find({'indexed':{'$exists':True}}).count()
print '已处理',num,'共计', self.pagesCollection.find().count() creatindext = CreatIndex()
creatindext.BuiltIndex()

注:注意编码

2、检索

from __future__ import unicode_literals
#coding=utf-8
__author__ = 'zh'
# from whoosh.qparser import QueryParser
from whoosh import qparser,sorting
# from jieba.analyse import ChineseAnalyzer
from whoosh.index import open_dir
from whoosh.query import *
# import pymongo
import datetime
# from pymongo.collection import Collection
# from pymongo import database class FullText:
def __init__(self,index_home='whoosh_index'):
self.index_home = index_home
self.ix = open_dir(self.index_home)
self.searcher = self.ix.searcher() # 全文检索,目前主要利用关键字
def Query(self,parameter):
# analyzer = ChineseAnalyzer()
# ix = open_dir(self.index_home) # for read only # searcher = ix.searcher()
# print ix.schema['content']
# 按照字段查询,可联合查询,MultifieldParser
list=parameter['keys']
if len(list)==1:
parser = qparser.QueryParser(list[0], schema=self.ix.schema)
if len(list)>1:
parser = qparser.MultifieldParser(list, schema=self.ix.schema)
# else:
# return None
# print ix.schema
keywords = parameter['keywords']
# print keywords
q = parser.parse(keywords) # mf = sorting.MultiFacet()
scores = sorting.ScoreFacet()
date = sorting.FieldFacet("publish_time", reverse=True) # 是否分页返回OR全部返回,默认全部返回
_limit=None
if parameter.has_key('page') and parameter.has_key('pagesize'):
page=parameter['page']
pagesize=parameter['pagesize']
if page > 0 and pagesize !=0:
_limit=page*pagesize # 是否按照location字段过滤,默认不过滤
allow_q=None
if parameter.has_key('includeFields') and parameter['includeFields'].__contains__(u'location'):
allow_q = qparser.query.Term("location", u"coordinates") # 时间分组,暂时不用
# start = datetime.datetime(2000, 1, 1)
# end = datetime.datetime.now()
# gap = datetime.timedelta(days=365)
# bdayfacet = sorting.DateRangeFacet("publish_time", start, end, gap) results = self.searcher.search(q, limit=_limit,filter=allow_q,sortedby=[scores,date])
# results = searcher.search(q, limit=_limit,filter=restrict_q,
# groupedby=bdayfacet,sortedby=[scores,date])
# print results.estimated_length()
return results
fulltext_query = fulltext.FullText()

注:支持多字段检索、分类、排序等

whoosh参考提供陕西省POI数据(300万条,sqlserver备份文件

利用whoosh对mongoDB的中文文档建立全文检索的更多相关文章

  1. python 搜索引擎Whoosh中文文档和代码 以及jieba的使用

    注意, 数据库的表最好别有下划线 中文文档链接: https://mr-zhao.gitbooks.io/whoosh/content/%E5%A6%82%E4%BD%95%E7%B4%A2%E5%B ...

  2. Phoenix综述(史上最全Phoenix中文文档)

    个人主页:http://www.linbingdong.com 简书地址:http://www.jianshu.com/users/6cb45a00b49c/latest_articles 网上关于P ...

  3. Django 1.10中文文档—第一个Django应用Part1

    在本教程中,我们将引导您完成一个投票应用程序的创建,它包含下面两部分: 一个可以进行投票和查看结果的公开站点: 一个可以进行增删改查的后台admin管理界面: 我们假设你已经安装了Django.您可以 ...

  4. 【Chromium中文文档】OS X 沙箱设计

    OS X 沙箱设计 转载请注明出处:https://ahangchen.gitbooks.io/chromium_doc_zh/content/zh//General_Architecture/OSX ...

  5. 【Chromium中文文档】Chrome/Chromium沙箱 - 安全架构设计

    沙箱 转载请注明出处:https://ahangchen.gitbooks.io/chromium_doc_zh/content/zh//General_Architecture/Sandbox.ht ...

  6. openstack中文文档

    http://www.openstack.cn/p392.html   openStack Hacker中文文档 http://docs.mirantis.com/fuel-dev/develop/a ...

  7. 【Chromium中文文档】进程模型

    进程模型 转载请注明出处:https://ahangchen.gitbooks.io/chromium_doc_zh/content/zh//General_Architecture/Process_ ...

  8. 【Chromium中文文档】Web安全研究

    转载请注明出处:https://ahangchen.gitbooks.io/chromium_doc_zh/content/zh//General_Architecture/Extension_Sec ...

  9. Visual Studio Code中文文档

    Visual Studio Code中文文档 Visual Studio Code是一个轻量级但是十分强大的源代码编辑器,重要的是它在Windows, OS X 和Linux操作系统的桌面上均可运行. ...

随机推荐

  1. 讨论MMU

    MMU是Memory Management Unit的缩写,中文名是内存管理单元,它是中央处理器(CPU)中用来管理虚拟存储器.物理存储器的控制线路,同时也负责虚拟地址映射为物理地址,以及提供硬件机制 ...

  2. Srtuts2实现登录界面(不连接数据库)报错(二)

    二月 28, 2014 11:37:29 下午 org.apache.catalina.core.AprLifecycleListener init 严重: An incompatible versi ...

  3. Docker 小记 — Compose & Swarm

    前言 任何相对完整的应用服务都不可能是由单一的程序来完成支持,计划使用 Docker 来部署的服务更是如此.大型服务需要进行拆分,形成微服务集群方能增强其稳定性和可维护性.本篇随笔将对 Docker ...

  4. CentOS配置samba服务

    1.服务器需要下载samba.sambaclient包 yum install samba samba-client -y 2.客户端需要下载samba-client.cifs-utils包 yum ...

  5. GitHub 错误解决

    1. The file will have its original line endings in your working directory. git config --global core. ...

  6. docker学习系列(一):docker 基础

    一.简介 开发当中比较麻烦的问题在于软件配置,每个人的机械以及系统都不尽相同,程序需要运行在系统当中需要配置好相应的系统以及各种依赖的组件,但是很多时候由于各种软件依赖包的版本,系统兼容性问题会导致程 ...

  7. C#图解教程 第十六章 转换

    转换 什么是转换隐式转换显式转换和强制转换 强制转换 转换的类型数字的转换 隐式数字转换溢出检测上下文 1.checked和unchecked运算符2.checked语句和unchecked语句 显式 ...

  8. 谈谈使用Redis缓存时批量删除的几种实现

    前言 在使用缓存的时候,我们时不时会遇到这样一个需求,根据缓存键的规则去批量删除这些数据,比较常见的就是按前缀去删除. 举个简单的例子,Redis中现在有几百个商品的数据,这些数据的key值是有一定规 ...

  9. [BZOJ2002] [Hnoi2010] Bounce 弹飞绵羊 (LCT)

    Description 某天,Lostmonkey发明了一种超级弹力装置,为了在他的绵羊朋友面前显摆,他邀请小绵羊一起玩个游戏.游戏一开始,Lostmonkey在地上沿着一条直线摆上n个装置,每个装置 ...

  10. python中的小知识点

    这里是一些小知识点的汇集,为的是以后查找的方便. 行与缩进: 物理行:实际看到的代码行数. 逻辑行:在意义上的函数(即解释器执行的行数) 如果一个物理行中包含了多个逻辑行,则每个逻辑行之间需要用分号 ...