文章目录
  1. 1. 一个简单封装操作的例子

一个xapian的document有term,value,data。term里面我放分词的结果用于搜索,value里面我放了日期用于排序,data我没放东西,然后根据xapian返回的docid在postgresql查找对应的文章。

取得估计的结果数

1
matches.get_matches_estimated()

对结果按时间进行排序

1
enquire.set_sort_by_value(1, True)

这里的 1 对应索引时的日期

在value中加入日期时间

1
xapian.sortable_serialise(time.mktime(posttime.timetuple()))

我这里是转换成时间戳,由于xapian的value需要存字符串,所以还需要用 xapian.sortable_serialise 序列化一下。

一个简单封装操作的例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import xapian, config
from mmseg.search import seg_txt_2_dict

class Xapian():
"""xapian search class """

def __init__(self):
"""init xapian search class
:returns: class

"""
self.db = xapian.WritableDatabase(config.xapian_index_dir, xapian.DB_CREATE_OR_OPEN)
self.enquire = xapian.Enquire(self.db)
self.enquire.set_sort_by_value(1, True)

def get_document(self, id):
"""获取doc

:id: id
:returns: Document

"""
return self.db.get_document(id)

def delete_document(self,id):
"""删除索引

:id: 索引id
"""
try:
return self.db.delete_document(id)
except:
return None

def update_index(self, id, text=None, values=None, data=None):
"""更新索引

:id: 要替换的id
:doc: 新的doc
"""
try:
doc = self.get_document(id)
except:
return False

if text:
doc.clear_terms()#清除terms
for word, value in seg_txt_2_dict(text).iteritems():
doc.add_term(word)

if values:
doc.clear_values()
for key, value in values.iteritems():
doc.add_value(key, value)

if data:
doc.set_data(data)

try:
self.db.replace_document(id, doc)
return True
except:
return False

def index(self, id, text, values={}, data=''):
"""index to xapian

:id: data id
:text: search content is utf-8
:returns: boolean

"""
doc = xapian.Document()
for word, value in seg_txt_2_dict(text).iteritems():
print word, value
doc.add_term(word)

#添加value用于排序,key似乎只能是数字
for key, value in values.iteritems():
doc.add_value(key, value)

if data:
doc.set_data(data)

try:
self.db.replace_document(id, doc)
return True
except:
return False

def search(self, keywords, offset=0, limit=10):
"""search xapian

:keywords: 搜索的关键字
:offset: 起始位置
:limit: 结束位置
:returns: matches对象

"""
query_list = []
for word, value in seg_txt_2_dict(keywords.encode('utf-8')).iteritems():
query = xapian.Query(word)
query_list.append(query)

if len(query_list) != 1:
query = xapian.Query(xapian.Query.OP_AND, query_list)
else:
query = query_list[0]

self.enquire.set_query(query)
matches = self.enquire.get_mset(offset, limit, 10000)
return matches

def flush(self):
"""flush to disk
:returns: flush结果

"""
return self.db.flush()

search = Xapian()
文章目录
  1. 1. 一个简单封装操作的例子