Fix whitespace irregularities in code
[xapian.git] / xapian-bindings / python / docs / examples / simplematchdecider.py
blobf6f9302c10cbc971d2b1509e6a704d49dd71ebf7
1 #!/usr/bin/env python
3 # Simple command-line match decider example
5 # Copyright (C) 2003 James Aylett
6 # Copyright (C) 2004,2007,2009 Olly Betts
8 # This program is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU General Public License as
10 # published by the Free Software Foundation; either version 2 of the
11 # License, or (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
21 # USA
23 import sys
24 import xapian
26 # This example runs a query like simplesearch does, but uses a MatchDecider
27 # (mymatchdecider) to discard any document for which value 0 is equal to
28 # the string passed as the second command line argument.
30 if len(sys.argv) < 4:
31 print >> sys.stderr, "Usage: %s PATH_TO_DATABASE AVOID_VALUE QUERY" % sys.argv[0]
32 sys.exit(1)
34 class mymatchdecider(xapian.MatchDecider):
35 def __init__(self, avoidvalue):
36 xapian.MatchDecider.__init__(self)
37 self.avoidvalue = avoidvalue
39 def __call__(self, doc):
40 return doc.get_value(0) != self.avoidvalue
42 try:
43 # Open the database for searching.
44 database = xapian.Database(sys.argv[1])
46 # Start an enquire session.
47 enquire = xapian.Enquire(database)
49 # Combine the rest of the command line arguments with spaces between
50 # them, so that simple queries don't have to be quoted at the shell
51 # level.
52 avoid_value = sys.argv[2]
53 query_string = str.join(' ', sys.argv[3:])
55 # Parse the query string to produce a Xapian::Query object.
56 qp = xapian.QueryParser()
57 stemmer = xapian.Stem("english")
58 qp.set_stemmer(stemmer)
59 qp.set_database(database)
60 qp.set_stemming_strategy(xapian.QueryParser.STEM_SOME)
61 query = qp.parse_query(query_string)
62 print "Parsed query is: %s" % str(query)
64 # Find the top 10 results for the query.
65 enquire.set_query(query)
66 mdecider = mymatchdecider(avoid_value)
67 matches = enquire.get_mset(0, 10, None, mdecider)
69 # Display the results.
70 print "%i results found." % matches.get_matches_estimated()
71 print "Results 1-%i:" % matches.size()
73 for m in matches:
74 print "%i: %i%% docid=%i [%s]" % (m.rank + 1, m.percent, m.docid, m.document.get_data())
76 except Exception, e:
77 print >> sys.stderr, "Exception: %s" % str(e)
78 sys.exit(1)