Add draft NEWS entries
[xapian.git] / xapian-core / examples / simplesearch.cc
bloba8d51b84bd66dc14306b2c27a3bb18326fda1122
1 /** @file
2 * @brief Simple command-line search utility.
4 * See "quest" for a more sophisticated example.
5 */
6 /* Copyright (C) 2007-2022 Olly Betts
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
23 #ifdef HAVE_CONFIG_H
24 # include <config.h>
25 #endif
27 #include <xapian.h>
29 #include <iostream>
30 #include <string>
32 #include <cstdlib> // For exit().
33 #include <cstring>
35 using namespace std;
37 int
38 main(int argc, char **argv)
39 try {
40 // We require at least two command line arguments.
41 if (argc < 3) {
42 int rc = 1;
43 if (argv[1]) {
44 if (strcmp(argv[1], "--version") == 0) {
45 cout << "simplesearch\n";
46 exit(0);
48 if (strcmp(argv[1], "--help") == 0) {
49 rc = 0;
52 cout << "Usage: " << argv[0] << " PATH_TO_DATABASE QUERY\n";
53 exit(rc);
56 // Open the database for searching.
57 Xapian::Database db(argv[1]);
59 // Start an enquire session.
60 Xapian::Enquire enquire(db);
62 // Combine the rest of the command line arguments with spaces between
63 // them, so that simple queries don't have to be quoted at the shell
64 // level.
65 string query_string(argv[2]);
66 argv += 3;
67 while (*argv) {
68 query_string += ' ';
69 query_string += *argv++;
72 // Parse the query string to produce a Xapian::Query object.
73 Xapian::QueryParser qp;
74 Xapian::Stem stemmer("english");
75 qp.set_stemmer(stemmer);
76 qp.set_database(db);
77 qp.set_stemming_strategy(Xapian::QueryParser::STEM_SOME);
78 Xapian::Query query = qp.parse_query(query_string);
79 cout << "Parsed query is: " << query.get_description() << '\n';
81 // Find the top 10 results for the query.
82 enquire.set_query(query);
83 Xapian::MSet matches = enquire.get_mset(0, 10);
85 // Display the results.
86 cout << matches.get_matches_estimated() << " results found.\n";
87 cout << "Matches 1-" << matches.size() << ":\n\n";
89 for (Xapian::MSetIterator i = matches.begin(); i != matches.end(); ++i) {
90 cout << i.get_rank() + 1 << ": " << i.get_weight() << " docid=" << *i
91 << " [" << i.get_document().get_data() << "]\n\n";
93 } catch (const Xapian::Error &e) {
94 cout << e.get_description() << '\n';
95 exit(1);