1#!/usr/bin/env python 2# 3# Simple command-line match decider example 4# 5# Copyright (C) 2003 James Aylett 6# Copyright (C) 2004,2007,2009 Olly Betts 7# 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. 12# 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. 17# 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 22 23import sys 24import xapian 25 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. 29 30if len(sys.argv) < 4: 31 print >> sys.stderr, "Usage: %s PATH_TO_DATABASE AVOID_VALUE QUERY" % sys.argv[0] 32 sys.exit(1) 33 34class mymatchdecider(xapian.MatchDecider): 35 def __init__(self, avoidvalue): 36 xapian.MatchDecider.__init__(self) 37 self.avoidvalue = avoidvalue 38 39 def __call__(self, doc): 40 return doc.get_value(0) != self.avoidvalue 41 42try: 43 # Open the database for searching. 44 database = xapian.Database(sys.argv[1]) 45 46 # Start an enquire session. 47 enquire = xapian.Enquire(database) 48 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:]) 54 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) 63 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) 68 69 # Display the results. 70 print "%i results found." % matches.get_matches_estimated() 71 print "Results 1-%i:" % matches.size() 72 73 for m in matches: 74 print "%i: %i%% docid=%i [%s]" % (m.rank + 1, m.percent, m.docid, m.document.get_data()) 75 76except Exception, e: 77 print >> sys.stderr, "Exception: %s" % str(e) 78 sys.exit(1) 79