-
-
Notifications
You must be signed in to change notification settings - Fork 47
/
search.cpp
370 lines (320 loc) · 10.8 KB
/
search.cpp
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
/*
* Copyright (C) 2017-2021 Matthieu Gautier <mgautier@kymeria.fr>
* Copyright (C) 2021 Maneesh P M <manu.pm55@gmail.com>
* Copyright (C) 2021 Veloman Yunkan
* Copyright (C) 2020 Emmanuel Engelhart <kelson@kiwix.org>
* Copyright (C) 2018 Kunal Mehta <legoktm@member.fsf.org>
* Copyright (C) 2007 Tommi Maekitalo
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* is provided AS IS, WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, and
* NON-INFRINGEMENT. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include <zim/error.h>
#include <zim/search.h>
#include <zim/archive.h>
#include <zim/item.h>
#include "fileimpl.h"
#include "search_internal.h"
#include "tools.h"
#include <sstream>
#include <sys/types.h>
#include <sys/stat.h>
#if !defined(_WIN32)
# include <unistd.h>
#else
# include <io.h>
#endif
#include "xapian.h"
#include <unicode/locid.h>
#include "constants.h"
#define MAX_MATCHES_TO_SORT 10000
namespace zim
{
InternalDataBase::InternalDataBase(const std::vector<Archive>& archives, bool verbose)
: m_verbose(verbose)
{
bool first = true;
m_queryParser.set_database(m_database);
m_queryParser.set_default_op(Xapian::Query::op::OP_AND);
for(auto& archive: archives) {
auto impl = archive.getImpl();
FileImpl::FindxResult r;
r = impl->findx('X', "fulltext/xapian");
if (!r.first) {
r = impl->findx('Z', "/fulltextIndex/xapian");
}
if (!r.first) {
continue;
}
auto xapianEntry = Entry(impl, entry_index_type(r.second));
auto accessInfo = xapianEntry.getItem().getDirectAccessInformation();
if (accessInfo.second == 0) {
continue;
}
Xapian::Database database;
if (!getDbFromAccessInfo(accessInfo, database)) {
continue;
}
try {
if ( first ) {
m_valuesmap = read_valuesmap(database.get_metadata("valuesmap"));
auto language = database.get_metadata("language");
if (language.empty() ) {
// Database created before 2017/03 has no language metadata.
// However, term were stemmed anyway and we need to stem our
// search query the same the database was created.
// So we need a language, let's use the one of the zim.
// If zimfile has no language metadata, we can't do lot more here :/
try {
language = archive.getMetadata("Language");
} catch(...) {}
}
if (!language.empty()) {
icu::Locale languageLocale(language.c_str());
/* Configuring language base steemming */
try {
m_stemmer = Xapian::Stem(languageLocale.getLanguage());
m_queryParser.set_stemmer(m_stemmer);
m_queryParser.set_stemming_strategy(Xapian::QueryParser::STEM_ALL);
} catch (...) {
std::cout << "No stemming for language '" << languageLocale.getLanguage() << "'" << std::endl;
}
}
auto stopwords = database.get_metadata("stopwords");
if ( !stopwords.empty() ){
std::string stopWord;
std::istringstream file(stopwords);
Xapian::SimpleStopper* stopper = new Xapian::SimpleStopper();
while (std::getline(file, stopWord, '\n')) {
stopper->add(stopWord);
}
stopper->release();
m_queryParser.set_stopper(stopper);
}
} else {
std::map<std::string, int> valuesmap = read_valuesmap(database.get_metadata("valuesmap"));
if (m_valuesmap != valuesmap ) {
// [TODO] Ignore the database, raise a error ?
}
}
m_xapianDatabases.push_back(database);
m_database.add_database(database);
m_archives.push_back(archive);
first = false;
} catch( Xapian::DatabaseError& e ) {
// [TODO] Ignore the database or raise a error ?
// As we already ignore the database if `getDbFromAccessInfo` "detects" a DatabaseError,
// we also ignore here.
}
}
}
bool InternalDataBase::hasDatabase() const
{
return !m_xapianDatabases.empty();
}
bool InternalDataBase::hasValuesmap() const
{
return !m_valuesmap.empty();
}
bool InternalDataBase::hasValue(const std::string& valueName) const
{
return (m_valuesmap.find(valueName) != m_valuesmap.end());
}
int InternalDataBase::valueSlot(const std::string& valueName) const
{
return m_valuesmap.at(valueName);
}
Xapian::Query InternalDataBase::parseQuery(const Query& query)
{
Xapian::Query xquery;
const auto unaccentedQuery = removeAccents(query.m_query);
xquery = m_queryParser.parse_query(unaccentedQuery, Xapian::QueryParser::FLAG_CJK_NGRAM);
if (query.m_geoquery && hasValue("geo.position")) {
Xapian::GreatCircleMetric metric;
Xapian::LatLongCoord centre(query.m_latitude, query.m_longitude);
Xapian::LatLongDistancePostingSource ps(valueSlot("geo.position"), centre, metric, query.m_distance);
Xapian::Query geoQuery(&ps);
if (unaccentedQuery.empty()) {
xquery = geoQuery;
} else {
xquery = Xapian::Query(Xapian::Query::OP_FILTER, xquery, geoQuery);
}
}
return xquery;
}
Searcher::Searcher(const std::vector<Archive>& archives) :
mp_internalDb(nullptr),
m_verbose(false)
{
for ( const auto& a : archives ) {
addArchive(a);
}
}
Searcher::Searcher(const Archive& archive) :
mp_internalDb(nullptr),
m_verbose(false)
{
addArchive(archive);
}
Searcher::Searcher(const Searcher& other) = default;
Searcher& Searcher::operator=(const Searcher& other) = default;
Searcher::Searcher(Searcher&& other) = default;
Searcher& Searcher::operator=(Searcher&& other) = default;
Searcher::~Searcher() = default;
namespace
{
bool archivesAreEquivalent(const Archive& a1, const Archive& a2)
{
return a1.getUuid() == a2.getUuid();
}
bool contains(const std::vector<Archive>& archives, const Archive& newArchive)
{
for ( const auto& a : archives ) {
if ( archivesAreEquivalent(a, newArchive) ) {
return true;
}
}
return false;
}
} // unnamed namespace
Searcher& Searcher::addArchive(const Archive& archive) {
if ( !contains(m_archives, archive) ) {
m_archives.push_back(archive);
mp_internalDb.reset();
}
return *this;
}
Search Searcher::search(const Query& query)
{
if (!mp_internalDb) {
initDatabase();
}
if (!mp_internalDb->hasDatabase()) {
throw(std::runtime_error("Cannot create Search without FT Xapian index"));
}
return Search(mp_internalDb, query);
}
void Searcher::setVerbose(bool verbose)
{
m_verbose = verbose;
}
void Searcher::initDatabase()
{
mp_internalDb = std::make_shared<InternalDataBase>(m_archives, m_verbose);
}
Search::Search(std::shared_ptr<InternalDataBase> p_internalDb, const Query& query)
: mp_internalDb(p_internalDb),
mp_enquire(nullptr),
m_query(query)
{
}
Search::Search(Search&& s) = default;
Search& Search::operator=(Search&& s) = default;
Search::~Search() = default;
Query::Query(const std::string& query) :
m_query(query)
{}
Query& Query::setQuery(const std::string& query) {
m_query = query;
return *this;
}
Query& Query::setGeorange(float latitude, float longitude, float distance) {
m_latitude = latitude;
m_longitude = longitude;
m_distance = distance;
m_geoquery = true;
return *this;
}
int Search::getEstimatedMatches() const
{
try {
auto enquire = getEnquire();
// Force xapian to check at least 10 documents even if we ask for an empty mset.
// Else, the get_matches_estimated may be wrong and return 0 even if we have results.
auto mset = enquire.get_mset(0, 0, 10);
return mset.get_matches_estimated();
} catch(Xapian::QueryParserError& e) {
return 0;
} catch(Xapian::DatabaseError& e) {
throw zim::ZimFileFormatError(e.get_description());
}
}
const SearchResultSet Search::getResults(int start, int maxResults) const {
try {
auto enquire = getEnquire();
auto mset = enquire.get_mset(start, maxResults);
return SearchResultSet(mp_internalDb, std::move(mset));
} catch(Xapian::QueryParserError& e) {
return SearchResultSet(mp_internalDb);
} catch(Xapian::DatabaseError& e) {
throw zim::ZimFileFormatError(e.get_description());
}
}
Xapian::Enquire& Search::getEnquire() const
{
if ( mp_enquire ) {
return *mp_enquire;
}
auto enquire = std::unique_ptr<Xapian::Enquire>(new Xapian::Enquire(mp_internalDb->m_database));
auto query = mp_internalDb->parseQuery(m_query);
if (mp_internalDb->m_verbose) {
std::cout << "Parsed query '" << m_query.m_query << "' to " << query.get_description() << std::endl;
}
enquire->set_query(query);
mp_enquire = std::move(enquire);
return *mp_enquire;
}
SearchResultSet::SearchResultSet(std::shared_ptr<InternalDataBase> p_internalDb, Xapian::MSet&& mset) :
mp_internalDb(p_internalDb),
mp_mset(std::make_shared<Xapian::MSet>(mset))
{}
SearchResultSet::SearchResultSet(std::shared_ptr<InternalDataBase> p_internalDb) :
mp_internalDb(p_internalDb),
mp_mset(nullptr)
{}
int SearchResultSet::size() const
{
if (! mp_mset) {
return 0;
}
try {
return mp_mset->size();
} catch(Xapian::DatabaseError& e) {
throw zim::ZimFileFormatError(e.get_description());
}
}
SearchResultSet::iterator SearchResultSet::begin() const
{
if ( ! mp_mset ) {
return nullptr;
}
try {
return new SearchIterator::InternalData(mp_internalDb, mp_mset, mp_mset->begin());
} catch(Xapian::DatabaseError& e) {
throw zim::ZimFileFormatError(e.get_description());
}
}
SearchResultSet::iterator SearchResultSet::end() const
{
if ( ! mp_mset ) {
return nullptr;
}
try {
return new SearchIterator::InternalData(mp_internalDb, mp_mset, mp_mset->end());
} catch(Xapian::DatabaseError& e) {
throw zim::ZimFileFormatError(e.get_description());
}
}
} //namespace zim