Make glass the default backend
[xapian.git] / xapian-core / docs / overview.rst
blob3f7cf93689cf78a0e8dbb0973fa4bae10790b730
1 Overview
2 ========
4 This document provides an introduction to the native C++ Xapian API.
5 This API provides programmers with the ability to index and search
6 through (potentially very large) bodies of data using probabilistic
7 methods.
9 *Note:* The portion of the API currently documented here covers only the
10 part of Xapian concerned with searching through existing databases, not
11 that concerned with creating them.
13 This document assumes you already have Xapian installed, so if you
14 haven't, it is a good idea to read `Installing Xapian <install.html>`_
15 first.
17 You may also wish to read the `Introduction
18 to Information Retrieval <intro_ir.html>`_ for a background into the
19 Information Retrieval theories behind Xapian.
21 This document does not detail the exact calling conventions (parameters
22 passed, return value, exceptions thrown, etc...) for each method in the
23 API. For such documentation, you should refer to the automatically
24 extracted documentation, which is generated from detailed comments in
25 the source code, and should thus remain up-to-date and accurate. This
26 documentation is generated using the
27 `Doxygen <http://www.doxygen.org/>`_ application. To save you having
28 to generate this documentation yourself, we include the `built
29 version <apidoc/html/index.html>`_ in our distributions, and also keep
30 the `latest version <https://xapian.org/docs/apidoc/html/index.html>`_ on
31 our website.
33 Design Principles
34 -----------------
36 API classes are either very lightweight or a wrapper around a reference
37 counted pointer (this style of class design is sometimes known as PIMPL
38 for "Private IMPLementation"). In either case copying is a cheap
39 operation as classes are at most a few words of memory.
41 API objects keep a reference to other objects they rely on so the user
42 doesn't need to worry about whether an object is still valid or not.
44 Where appropriate, API classes can be used as containers and iterators
45 just like those in the C++ STL.
47 Errors and exceptions
48 ---------------------
50 It is important to understand the errors which may be caused by the
51 operations which you are trying to perform.
53 This becomes particularly relevant when using a large system, with such
54 possibilities as databases which are being updated while you search
55 through them, and distributed enquiry systems.
57 Errors in Xapian are all reported by means of exceptions. All exceptions
58 thrown by Xapian will be subclasses of
59 `Xapian::Error <apidoc/html/classXapian_1_1Error.html>`_. Note that
60 ``Xapian::Error`` is an abstract class; thus you must catch exceptions
61 by reference rather than by value.
63 There are two flavours of error, derived from ``Xapian::Error``:
65 -  `Xapian::LogicError <apidoc/html/classXapian_1_1LogicError.html>`_
66    - for error conditions due to programming errors, such as a misuse of
67    the API. A finished application should not receive these errors
68    (though it would still be sensible to catch them).
69 -  `Xapian::RuntimeError <apidoc/html/classXapian_1_1RuntimeError.html>`_
70    - for error conditions due to run time problems, such as failure to
71    open a database. You must always be ready to cope with such errors.
73 Each of these flavours is further subdivided, such that any particular
74 error condition can be trapped by catching the appropriate exception. If
75 desired, a human readable explanation of the error can be retrieved by
76 calling
77 `Xapian::Error::get_msg() <apidoc/html/classXapian_1_1Error.html>`_.
79 In addition, standard system errors may occur: these will be reported by
80 throwing appropriate exceptions. Most notably, if the system runs out of
81 memory, a ``std::bad_alloc`` exception will be thrown.
83 Terminology
84 -----------
86 Databases
87 ~~~~~~~~~
89 These may also occasionally be called *Indexes*. In Xapian (as opposed
90 to a database package) a database consists of little more than indexed
91 documents: this reflects the purpose of Xapian as an information
92 retrieval system, rather than an information storage system.
94 The exact contents of a database depend on the type (see "`Database
95 Types <#database_types>`_" for more details of the database types
96 currently provided).
98 Queries
99 ~~~~~~~
101 The information to be searched for is specified by a *Query*. In Xapian,
102 queries are made up of a structured boolean tree, upon which
103 probabilistic weightings are imposed: when the search is performed, the
104 documents returned are filtered according to the boolean structure, and
105 weighted (and sorted) according to the probabilistic model of
106 information retrieval.
108 Memory handling
109 ---------------
111 The user of Xapian does not usually need to worry about how Xapian
112 performs its memory allocation: Xapian objects can all be created and
113 deleted as any other C++ objects. The convention is that whoever creates
114 an object is ultimately responsible for deleting it. This becomes
115 relevant when passing a pointer to data to Xapian: it will be the caller's
116 responsibility to delete the object once it is finished with.  Where
117 an object is set by one API call and used by another, Xapian will assume
118 that such pointers remain valid.
120 The Xapian::Enquire class
121 -------------------------
123 The `Xapian::Enquire <apidoc/html/classXapian_1_1Enquire.html>`_
124 class is central to all searching operations. It provides an interface
127 -  Specifying the database, or databases, to search across.
128 -  Specifying a query to perform.
129 -  Specifying a set of documents which a user considers relevant.
130 -  Given the supplied information, returning a ranked set of documents
131    for the user.
132 -  Given the supplied information, suggesting a ranked set of terms to
133    add to the query.
134 -  Returning information about the documents which matched, such as
135    their associated data, and which terms from the query were found
136    within them.
138 A typical enquiry session will consist of most of these operations, in
139 various orders. The Xapian::Enquire class presents as few restrictions
140 as possible on the order in which operations should be performed.
141 Although you must set the query before any operation which uses it, you
142 can call any of the other methods in any order.
144 Many operations performed by the Xapian::Enquire class are performed
145 lazily (ie, just before their results are needed). This need not concern
146 the user except to note that, as a result, errors may not be reported as
147 soon as would otherwise be expected.
149 Specifying a database
150 ---------------------
152 When creating a Xapian::Enquire object, a database to search must be
153 specified. Databases are specified by creating a `Xapian::Database
154 object <apidoc/html/classXapian_1_1Database.html>`_. Generally, you can
155 just construct the object, passing the pathname to the database. Xapian
156 looks at the path and autodetects the database type.
158 With the Remote backend, you need to use the ``Xapian::Remote::open()``
159 factory function.  The parameters you need to pass depend on whether
160 you're using the TCP or prog variant, and whether you are creating a read-only
161 or a writable database.
163 You can also create a "stub database" file which lists one or more
164 databases. These files are recognised by the autodetection in the
165 Database constructor (if the pathname is file rather than a directory,
166 it's treated as a stub database file, or if the pathname is a directory
167 containing a file called ``XAPIANDB``) or you can open them explicitly
168 using ``Xapian::DB_BACKEND_STUB``. The stub database format specifies one
169 database per line. For example::
171      remote localhost:23876
172      auto /var/spool/xapian/webindex
174 Database types
175 ~~~~~~~~~~~~~~
177 The current types understood by Xapian are:
179 auto
180     This isn't an actual database format, but rather auto-detection of one of
181     the disk based backends (e.g. "chert" or "glass") from a single specified
182     path (which can be to a file or directory).
184 glass
185     Glass is the default backend in Xapian 1.4.x. It supports incremental
186     modifications, concurrent single-writer and multiple-reader access to a
187     database. It's very efficient and highly scalable, and more compact than
188     chert.
190 chert
191     Chert was the default backend in Xapian 1.2.x. It supports incremental
192     modifications, concurrent single-writer and multiple-reader access to a
193     database. It's very efficient and highly scalable.
195 inmemory
196     This type is a database held entirely in memory. It was originally written
197     for testing purposes only, but may prove useful for building up temporary
198     small databases.
200 remote
201     This can specify either a "program" or TCP remote backend, for example::
203         remote :ssh xapian-prog.example.com xapian-progsrv /srv/xapian/db1
205     or::
207         remote xapian-tcp.example.com:12345
209     If the first character of the second word is a colon (``:``), then this is
210     skipped and the remainder of the line is used as the command to run
211     xapian-progsrv and the "program" variant of the remote backend is used.
212     Otherwise the TCP variant of the remote backend is used, and the rest of
213     the line specifies the host and port to connect to.
215 These are no longer supported by Xapian 1.4.x:
217 brass
218     Brass was the current "under development" database format in Xapian 1.2.x,
219     1.3.0 and 1.3.1.  It was renamed to 'glass' in Xapian 1.3.2 because we
220     decided to use backend names in ascending alphabetical order to make it
221     easier to understand which backend is newest, and since 'flint' was used
222     recently, we skipped over 'd', 'e' and 'f'.
224 flint
225     Flint was the default backend in Xapian 1.0.x, and was deprecated in
226     1.2.x and removed in 1.3.0.  If you want to migrate an existing Flint
227     database to Chert, `see the 'Admin Notes'
228     <admin_notes.html#converting-a-flint-database-to-a-chert-database%60>`_
229     for a way to do this.
231 quartz
232     Quartz was the default backend prior to Xapian 1.0, and has been removed as
233     of Xapian 1.1.0. If you want to migrate an existing Quartz database to
234     Flint, see `Admin Notes
235     <admin_notes.html#converting-a-quartz-database-to-a-flint-database%60>`_
236     for a way to do this.
238 Multiple databases
239 ~~~~~~~~~~~~~~~~~~
241 Xapian can search across several databases as easily as searching across
242 a single one. Simply call
243 `Xapian::Database::add_database() <apidoc/html/classXapian_1_1Database.html>`_
244 for each database that you wish to search through.
246 You can also set up "pre-canned" listed of databases to search over
247 using a "stub database" - see above for details.
249 Specifying a query
250 ------------------
252 Xapian implements both boolean and probabilistic searching. There are
253 two obvious ways in which a pure boolean query could be combined with a
254 pure probabilistic query:
256 -  First perform the boolean search to create a subset of the whole
257    document collection, and then do the probabilistic search on this
258    subset, or
259 -  Do the probabilistic search, and then filter out the resulting
260    documents with a boolean query.
262 There is in fact a subtle difference in these two approaches. In the
263 first, the collection statistics for the probabilistic query will be
264 determined by the document subset which is obtained by running the
265 boolean query. In the second, the collection statistics for the
266 probabilistic query are determined by the whole document collection.
267 These differences can affect the final result.
269 Suppose for example the boolean query is being used to retrieve
270 documents in English in a database containing English and French
271 documents. A word like "*grand*", exists in both languages (with similar
272 meanings), but is more common in French than English. In the English
273 subset it could therefore be expected to have a higher weight than it
274 would get in the joint English and French databases.
276 Xapian takes the second approach simply because this can be implemented
277 very efficiently. The first approach is more exact, but inefficient to
278 implement.
280 Rather than implementing this approach as described above and first
281 performing the probabilistic search and then filtering the results,
282 Xapian actually performs both tasks simultaneously. This allows various
283 optimisations to be performed, such as giving up on calculating a
284 boolean AND operation when the probabilistic weights that could result
285 from further documents can have no effect on the result set. These
286 optimisations have been found to often give a several-fold performance
287 increase. The performance is particularly good for queries containing
288 many terms.
290 A query for a single term
291 ~~~~~~~~~~~~~~~~~~~~~~~~~
293 A search query is represented by a
294 `Xapian::Query <apidoc/html/classXapian_1_1Query.html>`_ object. The
295 simplest useful query is one which searches for a single term (and
296 several of these can be combined to form more complex queries). A single
297 term query can be created as follows (where ``term`` is a
298 ``std::string`` holding the term to be searched for)::
300     Xapian::Query query(term);
302 A term in Xapian is represented simply by a string of bytes.  Usually, when
303 searching text, these bytes will represent the characters of the word which
304 the term represents, but during the information retrieval process Xapian
305 attaches no specific meaning to the term.
307 This constructor actually takes a couple of extra parameters, which may
308 be used to specify positional and frequency information for terms in the
309 query::
311     Xapian::Query(const string & tname_,
312             Xapian::termcount wqf_ = 1,
313             Xapian::termpos term_pos_ = 0)
315 The ``wqf`` (Within Query Frequency) is a measure of how common a term is
316 in the query. This isn't useful for a single term query unless it is going
317 to form part of a more complex query. In that case, it's particularly
318 useful when generating a query from an existing document, but may also be
319 used to increase the "importance" of a term in a query. Another way to
320 increase the "importance" of a term is to use ``OP_SCALE_WEIGHT``. But if
321 the intention is simply to ensure that a particular term is in the query
322 results, you should use a boolean AND or AND\_MAYBE rather than setting a
323 high wqf.
325 The ``term_pos`` represents the position of the term in the query.
326 Again, this isn't useful for a single term query by itself, but is used
327 for phrase searching, passage retrieval, and other operations which
328 require knowledge of the order of terms in the query (such as returning
329 the set of matching terms in a given document in the same order as they
330 occur in the query). If such operations are not required, the default
331 value of 0 may be used.
333 Note that it may not make much sense to specify a wqf other than 1 when
334 supplying a term position (unless you are trying to affect the
335 weighting, as previously described).
337 Note also that the results of ``Xapian::Query(tname, 2)`` and
338 ``Xapian::Query(Xapian::Query::OP_OR, Xapian::Query(tname), Xapian::Query(tname))``
339 are exactly equivalent.
341 Compound queries
342 ~~~~~~~~~~~~~~~~
344 Compound queries can be built up from single term queries by combining
345 them a connecting operator. Most operators can operate on either a
346 single term query or a compound query. You can combine pair-wise using
347 the following constructor::
349     Xapian::Query(Xapian::Query::op op_,
350             const Xapian::Query & left,
351             const Xapian::Query & right)
353 The two most commonly used operators are ``Xapian::Query::OP_AND`` and
354 ``Xapian::Query::OP_OR``, which enable us to construct boolean queries
355 made up from the usual AND and OR operations. But in addition to this, a
356 probabilistic query in its simplest form, where we have a list of terms
357 which give rise to weights that need to be added together, is also made
358 up from a set of terms joined together with ``Xapian::Query::OP_OR``.
360 Some of the available ``Xapian::Query::op`` operators are:
362 +---------------------------------+-----------------------------------------------------------------------------------------------------------------------+
363 | Xapian::Query::OP\_AND          | Return documents returned by both subqueries.                                                                         |
364 +---------------------------------+-----------------------------------------------------------------------------------------------------------------------+
365 | Xapian::Query::OP\_OR           | Return documents returned by either subquery.                                                                         |
366 +---------------------------------+-----------------------------------------------------------------------------------------------------------------------+
367 | Xapian::Query::OP\_AND\_NOT     | Return documents returned by the left subquery but not the right subquery.                                            |
368 +---------------------------------+-----------------------------------------------------------------------------------------------------------------------+
369 | Xapian::Query::OP\_FILTER       | As Xapian::Query::OP\_AND, but use only weights from left subquery.                                                   |
370 +---------------------------------+-----------------------------------------------------------------------------------------------------------------------+
371 | Xapian::Query::OP\_AND\_MAYBE   | Return documents returned by the left subquery, but adding document weights from both subqueries.                     |
372 +---------------------------------+-----------------------------------------------------------------------------------------------------------------------+
373 | Xapian::Query::OP\_XOR          | Return documents returned by one subquery only.                                                                       |
374 +---------------------------------+-----------------------------------------------------------------------------------------------------------------------+
375 | Xapian::Query::OP\_NEAR         | Return documents where the terms are with the specified distance of each other.                                       |
376 +---------------------------------+-----------------------------------------------------------------------------------------------------------------------+
377 | Xapian::Query::OP\_PHRASE       | Return documents where the terms are with the specified distance of each other and in the given order.                |
378 +---------------------------------+-----------------------------------------------------------------------------------------------------------------------+
379 | Xapian::Query::OP\_ELITE\_SET   | Select an elite set of terms from the subqueries, and perform a query with all those terms combined as an OR query.   |
380 +---------------------------------+-----------------------------------------------------------------------------------------------------------------------+
382 Understanding queries
383 ~~~~~~~~~~~~~~~~~~~~~
385 Each term in the query has a weight in each document. Each document may
386 also have an additional weight not associated with any of the terms. By
387 default the probabilistic weighting scheme `BM25 <bm25.html>`_ is used
388 to provide the formulae which give these weights.
390 A query can be thought of as a tree structure. At each node is an
391 ``Xapian::Query::op`` operator, and on the left and right branch are two
392 other queries. At each leaf node is a term, t, transmitting documents
393 and scores, D and w\ :sub:`D`\ (t), up the tree.
395 A Xapian::Query::OP\_OR node transmits documents from both branches up
396 the tree, summing the scores when a document is found in both the left
397 and right branch. For example,
400                                docs       1    8    12    16    17    18
401                                scores    7.3  4.1   3.2  7.6   3.8   4.7 ...
402                                  |
403                                  |
404                        Xapian::Query::OP_OR
405                              /       \
406                             /         \
407                            /           \
408                           /             \
409        docs     1   12   16   17         1   8   16   18
410        scores  3.1 3.2  3.1  3.8 ...    4.2 4.1 4.5  4.7 ...
412 A Xapian::Query::OP\_AND node transmits only the documents found on both
413 branches up the tree, again summing the scores,
416                                docs       1   16
417                                scores    7.3  7.6  ...
418                                  |
419                                  |
420                        Xapian::Query::OP_AND
421                              /       \
422                             /         \
423                            /           \
424                           /             \
425        docs     1   12   16   17         1   8   16   18
426        scores  3.1 3.2  3.1  3.8 ...    4.2 4.1 4.5  4.7 ...
428 A Xapian::Query::OP\_AND\_NOT node transmits up the tree the documents
429 on the left branch which are not on the right branch. The scores are
430 taken from the left branch. For example, again summing the scores,
433                                docs       12   17
434                                scores    3.2  3.8 ...
435                                  |
436                                  |
437                      Xapian::Query::OP_AND_NOT
438                              /       \
439                             /         \
440                            /           \
441                           /             \
442        docs     1   12   16   17         1   8   16   18
443        scores  3.1 3.2  3.1  3.8 ...    4.2 4.1 4.5  4.7 ...
445 A Xapian::Query::OP\_AND\_MAYBE node transmits the documents up the tree
446 from the left branch only, but adds in the score from the right branch
447 for documents which occur on both branches. For example,
450                                docs       1    12   16   17
451                                scores    7.3  3.2  7.6  3.8 ...
452                                  |
453                                  |
454                     Xapian::Query::OP_AND_MAYBE
455                              /       \
456                             /         \
457                            /           \
458                           /             \
459        docs     1   12   16   17         1   8   16   18
460        scores  3.1 3.2  3.1  3.8 ...    4.2 4.1 4.5  4.7 ...
462 Xapian::Query::OP\_FILTER is like Xapian::Query::OP\_AND, but weights
463 are only transmitted from the left branch. For example,
466                                docs       1   16
467                                scores    3.1  3.1  ...
468                                  |
469                                  |
470                       Xapian::Query::OP_FILTER
471                              /       \
472                             /         \
473                            /           \
474                           /             \
475        docs     1   12   16   17         1   8   16   18
476        scores  3.1 3.2  3.1  3.8 ...    4.2 4.1 4.5  4.7 ...
478 Xapian::Query::OP\_XOR is like Xapian::Query::OP\_OR, but documents on
479 both left and right branches are not transmitted up the tree. For
480 example,
483                                docs       8    12    17    18
484                                scores    4.1   3.2  3.8   4.7 ...
485                                  |
486                                  |
487                           Xapian::Query::OP_XOR
488                              /       \
489                             /         \
490                            /           \
491                           /             \
492        docs     1   12   16   17         1   8   16   18
493        scores  3.1 3.2  3.1  3.8 ...    4.2 4.1 4.5  4.7 ...
495 A query can therefore be thought of as a process for generating an MSet
496 from the terms at the leaf nodes of the query. Each leaf node gives rise
497 to a posting list of documents with scores. Each higher level node gives
498 rise to a similar list, and the root node of the tree contains the final
499 set of documents with scores (or weights), which are candidates for
500 going into the MSet. The MSet contains the documents which get the
501 highest weights, and they are held in the MSet in weight order.
503 It is important to realise that within Xapian the structure of a query
504 is optimised for best performance, and it undergoes various
505 transformations as the query progresses. The precise way in which the
506 query is built up is therefore of little importance to Xapian - for
507 example, you can AND together terms pair-by-pair, or combine several
508 using AND on a std::vector of terms, and Xapian will build the same
509 structure internally.
511 Using queries
512 ~~~~~~~~~~~~~
514 Probabilistic queries
515 ^^^^^^^^^^^^^^^^^^^^^
517 A plain probabilistic query is created by connecting terms together with
518 Xapian::Query::OP\_OR operators. For example,
521         Xapian::Query query("regulation");
522         query = Xapian::Query(Xapian::Query::OP_OR, query, Xapian::Query("import"));
523         query = Xapian::Query(Xapian::Query::OP_OR, query, Xapian::Query("export"));
524         query = Xapian::Query(Xapian::Query::OP_OR, query, Xapian::Query("canned"));
525         query = Xapian::Query(Xapian::Query::OP_OR, query, Xapian::Query("fish"));
527 This creates a probabilistic query with terms `regulation`, `import`,
528 `export`, `canned` and `fish`.
530 In fact this style of creation is so common that there is the shortcut
531 construction::
533         vector<string> terms;
534         terms.push_back("regulation");
535         terms.push_back("import");
536         terms.push_back("export");
537         terms.push_back("canned");
538         terms.push_back("fish");
540         Xapian::Query query(Xapian::Query::OP_OR, terms.begin(), terms.end());
542 Boolean queries
543 ^^^^^^^^^^^^^^^
545 Suppose now we have this Boolean query,
548         ('EEC' - 'France') and ('1989' or '1991' or '1992') and 'Corporate_Law'
550 This could be built up as bquery like this,
553         Xapian::Query bquery1(Xapian::Query::OP_AND_NOT, "EEC", "France");
555         Xapian::Query bquery2("1989");
556         bquery2 = Xapian::Query(Xapian::Query::OP_OR, bquery2, "1991");
557         bquery2 = Xapian::Query(Xapian::Query::OP_OR, bquery2, "1992");
559         Xapian::Query bquery3("Corporate_Law");
561         Xapian::Query bquery(Xapian::Query::OP_AND, bquery1, Xapian::Query(Xapian::Query::OP_AND(bquery2, bquery3)));
563 and this can be attached as a filter to ``query`` to run the
564 probabilistic query with a Boolean filter,
567         query = Xapian::Query(Xapian::Query::OP_FILTER, query, bquery);
569 If you want to run a pure boolean query, then set BoolWeight as the
570 weighting scheme (by calling Enquire::set\_weighting\_scheme() with
571 argument BoolWeight()).
573 Plus and minus terms
574 ^^^^^^^^^^^^^^^^^^^^
576 A common requirement in search engine functionality is to run a
577 probabilistic query where some terms are required to index all the
578 retrieved documents (`+` terms), and others are required to index none
579 of the retrieved documents (`-` terms). For example,
582         regulation import export +canned +fish -japan
584 the corresponding query can be set up by,
587         vector<string> plus_terms;
588         vector<string> minus_terms;
589         vector<string> normal_terms;
591         plus_terms.push_back("canned");
592         plus_terms.push_back("fish");
594         minus_terms.push_back("japan");
596         normal_terms.push_back("regulation");
597         normal_terms.push_back("import");
598         normal_terms.push_back("export");
600         Xapian::Query query(Xapian::Query::OP_AND_MAYBE,
601                       Xapian::Query(Xapian::Query::OP_AND, plus_terms.begin(), plus_terms.end());
602                       Xapian::Query(Xapian::Query::OP_OR, normal_terms.begin(), normal_terms.end()));
604         query = Xapian::Query(Xapian::Query::OP_AND_NOT,
605                         query,
606                         Xapian::Query(Xapian::Query::OP_OR, minus_terms.begin(), minus_terms.end()));
608 Undefined queries
609 ~~~~~~~~~~~~~~~~~
611 Performing a match with an undefined query matches nothing, which is
612 sometimes useful. Composing an undefined query with operators behaves
613 just as it would for any subquery which matches nothing.
615 Retrieving the results of a query
616 ---------------------------------
618 To get the results of the query, call the ``Enquire::get_mset()`` method::
620     Xapian::MSet Xapian::Enquire::get_mset(Xapian::doccount first,
621                                Xapian::doccount maxitems,
622                                const Xapian::RSet * rset = 0,
623                                const Xapian::MatchDecider * mdecider = 0) const
625 When asking for the results, you must specify (in ``first``) the first
626 item in the result set to return, where the numbering starts at zero (so
627 a value of zero corresponds to the first item returned being that with
628 the highest score, and a value of 10 corresponds to the first 10 items
629 being ignored, and the returned items starting at the eleventh).
631 You must also specify (in ``maxitems``) the maximum number of items to
632 return. Unless there are not enough matching items, precisely this
633 number of items will be returned. If ``maxitems`` is zero, no items will
634 be returned, but the usual statistics (such as the maximum possible
635 weight which a document could be assigned by the query) will be
636 calculated. (See "The Xapian::MSet" below).
638 The Xapian::MSet
639 ~~~~~~~~~~~~~~~~
641 Query results are returned in an
642 `Xapian::MSet <apidoc/html/classXapian_1_1MSet.html>`_ object. The
643 results can be accessed using a
644 `Xapian::MSetIterator <apidoc/html/classXapian_1_1MSetIterator.html>`_
645 which returns the matches in descending sorted order of relevance (so
646 the most relevant document is first in the list). Each ``Xapian::MSet``
647 entry comprises a document id, and the weight calculated for that
648 document.
650 An ``Xapian::MSet`` also contains various information about the search
651 result:
653 firstitem
654     The index of the first item in the result which was put into the MSet.
655     (Corresponding to ``first`` in ``Xapian::Enquire::get_mset()``)
656 max_attained
657     The greatest weight which is attained in the full results of the search.
658 max_possible
659     The maximum possible weight in the MSet.
660 docs_considered
661     The number of documents matching the query considered for the MSet. This
662     provides a lower bound on the number of documents in the database which
663     have a weight greater than zero. Note that this value may change if the
664     search is recalculated with different values for ``first`` or
665     ``max_items``.
667 See the `automatically extracted
668 documentation <apidoc/html/classXapian_1_1MSet.html>`_ for more details
669 of these fields.
671 The ``Xapian::MSet`` also provides methods for converting the score
672 calculated for a given document into a percentage value, suitable for
673 displaying to a user. This may be done using the
674 `convert_to_percent() <apidoc/html/classXapian_1_1MSet.html>`_
675 methods::
677          int Xapian::MSet::convert_to_percent(const Xapian::MSetIterator & item) const
678          int Xapian::MSet::convert_to_percent(double wt) const
680 These methods return a value in the range 0 to 100, which will be 0 if
681 and only if the item did not match the query at all.
683 Accessing a document
684 ~~~~~~~~~~~~~~~~~~~~
686 A document in the database is accessed via a
687 `Xapian::Document <apidoc/html/classXapian_1_1Document.html>`_
688 object. This can be obtained by calling
689 `Xapian::Database::get_document() <apidoc/html/classXapian_1_1Database.html>`_.
690 The returned ``Xapian::Document`` is a reference counted handle so
691 copying is cheap.
693 Each document can have the following types of information associated
694 with it:
696 -  document data - this is an arbitrary block of data accessed using
697    `Xapian::Document::get_data() <apidoc/html/classXapian_1_1Document.html>`_.
698    The contents of the document data can be whatever you want and in
699    whatever format. Often it contains fields such as a URL or other
700    external UID, a document title, and an excerpt from the document
701    text. If you wish to interoperate with Omega, it should contain
702    name=value pairs, one per line (recent versions of Omega also support
703    one field value per line, and can assign names to line numbers in the
704    query template).
705 -  terms and positional information - terms index the document (like
706    index entries in the back of a book); positional information records
707    the word offset into the document of each occurrence of a particular
708    term. This is used to implement phrase searching and the NEAR
709    operator.
710 -  document values - these are arbitrary pieces of data which are stored
711    so they can be accessed rapidly during the match process (to allow
712    sorting collapsing of duplicates, etc). Each value is stored in a
713    numbered slot so you can have several for each document. There's
714    currently no length limit, but you should keep them short for
715    efficiency.
717 There's some overlap in what you can do with terms and with values. A
718 simple boolean operator (e.g. document language) is definitely better
719 done using a term and OP\_FILTER.
721 Using a value allows you to do things you can't do with terms, such as
722 "sort by price", or "show only the best match for each website". You can
723 also perform filtering with a value which is more sophisticated than can
724 easily be achieved with terms, for example: find matches with a price
725 between $100 and $900. Omega uses boolean terms to perform date range
726 filtering, but this might actually be better done using a value (the
727 code in Omega was written before values were added to Xapian).
729 Specifying a relevance set
730 --------------------------
732 Xapian supports the idea of relevance feedback: that is, of allowing the
733 user to mark documents as being relevant to the search, and using this
734 information to modify the search. This is supported by means of
735 relevance sets, which are simply sets of document ids which are marked
736 as relevant. These are held in
737 `Xapian::RSet <apidoc/html/classXapian_1_1RSet.html>`_ objects, one
738 of which may optionally be supplied to Xapian in the ``rset``
739 parameter when calling ``Xapian::Enquire::get_mset()``.
741 Match options
742 ~~~~~~~~~~~~~
744 There are various additional options which may be specified when
745 performing the query. These are specified by calling `various methods of
746 the Xapian::Enquire object <apidoc/html/classXapian_1_1Enquire.html>`_.
747 The options are as follows.
749 collapse key
750     Each document in a database may have a set of numbered value slots. The
751     contents of each value slot is a string of arbitrary length. The
752     ``set_collapse_key(Xapian::valueno collapse_key)`` method specifies a
753     value slot number upon which to remove duplicates. Only the most
754     recently set duplicate removal key is active at any time, and the
755     default is to perform no duplicate removal.
756 percentage cutoff
757     It may occasionally be desirable to exclude any documents which have a
758     weight less than a given percentage value. This may be done using
759     ``set_cutoff(Xapian::percent percent_cutoff)``.
760 sort direction
761     Some weighting functions may frequently result in several documents being
762     returned with the same weight. In this case, by default, the documents will
763     be returned in ascending document id order. This can be changed by using
764     ``set_docid_order()`` to set the sort direction.
766     ``set_docid_order(Xapian::Enquire::DESCENDING)`` may be useful, for
767     example, when it would be best to return the newest documents, and new
768     documents are being added to the end of the database (which is what happens
769     by default).
771 Match decision functors
772 ~~~~~~~~~~~~~~~~~~~~~~~
774 Sometimes it may be useful to return only documents matching criteria
775 which can't be easily represented by queries. This can be done using a
776 match decision functor. To set such a condition, derive a class from
777 ``Xapian::MatchDecider`` and override the function operator,
778 ``operator()(const Xapian::Document &doc)``. The operator can make a
779 decision based on the document values via
780 ``Xapian::Document::get_value(Xapian::valueno)``.
782 The functor will also have access to the document data stored in the
783 database (via ``Xapian::Document::get_data()``), but beware that for
784 most database backends, this is an expensive operation to be calling
785 for a lot of documents, so doing that is likely to slow down the search
786 considerably.
788 Expand - Suggesting new terms for the query
789 -------------------------------------------
791 Xapian also supports the idea of calculating terms to add to the query,
792 based on the relevant documents supplied. A set of such terms, together
793 with their weights, may be returned by:
796     Xapian::ESet Xapian::Enquire::get_eset(Xapian::termcount maxitems,
797                                const Xapian::RSet & rset,
798                    bool exclude_query_terms = true,
799                    bool use_exact_termfreq = false,
800                    double k = 1.0,
801                    const Xapian::ExpandDecider * edecider = 0) const;
802     Xapian::ESet Xapian::Enquire::get_eset(Xapian::termcount maxitems,
803                                const Xapian::RSet & rset,
804                                const Xapian::ExpandDecider * edecider) const
806 As for ``get_mset``, up to ``maxitems`` expand terms will be returned,
807 with fewer being returned if and only if no more terms could be found.
809 The expand terms are returned in sorted weight order in an
810 `Xapian::ESet <apidoc/html/classXapian_1_1ESet.html>`_ item.
812 exclude\_query\_terms
813 ~~~~~~~~~~~~~~~~~~~~~
815 By default terms which are already in the query will never be returned
816 by ``get_eset()``. If ``exclude_query_terms`` is ``false``) then query
817 terms may be returned.
819 use\_exact\_termfreq
820 ~~~~~~~~~~~~~~~~~~~~
822 By default, Xapian uses an approximation to the term frequency when
823 ``get_eset()`` is called when searching over multiple databases. This
824 approximation improves performance, and usually still returns good
825 results. If you're willing to pay the performance penalty, you can get
826 Xapian to calculate the exact term frequencies by passing ``true`` for
827 ``use_exact_termfreq``.
829 Expand decision functors
830 ~~~~~~~~~~~~~~~~~~~~~~~~
832 It is often useful to allow only certain classes of term to be returned
833 in the expand set. For example, there may be special terms in the
834 database with various prefixes, which should be removed from the expand
835 set. This is accomplished by providing a decision functor. To do this,
836 derive a class from ``Xapian::ExpandDecider`` and override the function
837 operator, ``operator()(const string &)``. The functor is called with
838 each term before it is added to the set, and it may accept (by returning
839 ``true``) or reject (by returning ``false``) the term as appropriate.
841 Thread safety
842 -------------
844 There's no pthread specific code in Xapian. If you want to use the same
845 object concurrently from different threads, it's up to you to police
846 access (with a mutex or in some other way) to ensure only one method is
847 being executed at once. The reason for this is to avoid adding the
848 overhead of locking and unlocking mutexes when they aren't required. It
849 also makes the Xapian code easier to maintain, and simplifies building
852 For most applications, this is unlikely to be an issue - generally the
853 calls to Xapian are likely to be from a single thread. And if they
854 aren't, you can just create an entirely separate Xapian::Database object
855 in each thread - this is no different to accessing the same database
856 from two different processes.
858 Examples
859 --------
861 Examples of usage of Xapian are available in the examples
862 subdirectory of xapian-core.