Navigation

  • index
  • next |
  • previous |
  • Getting Started with Xapian v1.4 »
  • A practical example »
  • Searching »

Building the searchΒΆ

Now we have our database populated with some values, it is time for the code to search the database and display some results.

We want to take some text from the user, and search for it in the database; to do that we need to convert it into a Xapian Query, which you will recall is a tree made up of terms (which in this case will be the stemmed forms of words in the text from the user), and operations such as AND, OR and so forth.

There are many ways to go from the user’s text to a Query, but the most simple of these is to use the QueryParser. We then pass the Query to an Enquire object, which also needs setting up with a database, and is where you’d set various other options that affect how the query is run (such as sorting, for instance) which we won’t address here.

static void
search(const string & dbpath, const string & querystring,
       Xapian::doccount offset = 0, Xapian::doccount pagesize = 10)
{
    // offset - defines starting point within result set.
    // pagesize - defines number of records to retrieve.

    // Open the database we're going to search.
    Xapian::Database db(dbpath);

    // Set up a QueryParser with a stemmer and suitable prefixes.
    Xapian::QueryParser queryparser;
    queryparser.set_stemmer(Xapian::Stem("en"));
    queryparser.set_stemming_strategy(queryparser.STEM_SOME);
    // Start of prefix configuration.
    queryparser.add_prefix("title", "S");
    queryparser.add_prefix("description", "XD");
    // End of prefix configuration.

    // And parse the query.
    Xapian::Query query = queryparser.parse_query(querystring);

    // Use an Enquire object on the database to run the query.
    Xapian::Enquire enquire(db);
    enquire.set_query(query);

    // And print out something about each match.
    Xapian::MSet mset = enquire.get_mset(offset, pagesize);

    clog << "'" << querystring << "'[" << offset << ":" << offset + pagesize
	 << "] =";
    for (Xapian::MSetIterator m = mset.begin(); m != mset.end(); ++m) {
	Xapian::docid did = *m;
	cout << m.get_rank() + 1 << ": #" << setfill('0') << setw(3) << did
	     << ' ';

	const size_t DOC_FIELD_TITLE = 1;
	const string & data = m.get_document().get_data();
	cout << get_field(data, DOC_FIELD_TITLE) << endl;
	// Log the document id.
	clog << ' ' << did;
    }
    clog << endl;
}

A full copy of this code is available in code/c++/search1.cc.

Previous topic

Searching

Next topic

Running a Search

This Page

  • Show Source

Quick search

Navigation

  • index
  • next |
  • previous |
  • Getting Started with Xapian v1.4 »
  • A practical example »
  • Searching »
© Copyright 2003-2017 Xapian Documentation Team & Contributors. Created using Sphinx 1.4.9.