3 # Simple example script demonstrating query expansion.
5 # Originally by Paul Legato (plegato@nks.net), 4/22/06.
7 # Copyright (C) 2006 Networked Knowledge Systems, Inc.
8 # Copyright (C) 2006,2007,2016 Olly Betts
10 # This program is free software; you can redistribute it and/or
11 # modify it under the terms of the GNU General Public License as
12 # published by the Free Software Foundation; either version 2 of the
13 # License, or (at your option) any later version.
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
20 # You should have received a copy of the GNU General Public License
21 # along with this program; if not, write to the Free Software
22 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
28 $stderr.puts "Usage: #{$0} PATH_TO_DATABASE QUERY [-- [DOCID...]]"
32 # Open the database for searching.
33 database = Xapian::Database.new(ARGV[0])
35 # Start an enquire session.
36 enquire = Xapian::Enquire.new(database)
39 relevant_docs = Xapian::RSet.new()
40 on_doc_ids_yet = false
42 # Combine the rest of the command line arguments with spaces between
43 # them, so that simple queries don't have to be quoted at the shell
45 ARGV.each_with_index { |arg,index|
46 next if index == 0 # skip path to db
54 relevant_docs.add_document(arg.to_i)
56 query_string += ' ' unless query_string.empty?
62 # Parse the query string to produce a Xapian::Query object.
63 qp = Xapian::QueryParser.new()
64 stemmer = Xapian::Stem.new("english")
66 qp.database = database
67 qp.stemming_strategy = Xapian::QueryParser::STEM_SOME
68 query = qp.parse_query(query_string)
71 puts "Parsed query is: #{query.description()}"
73 # Find the top 10 results for the query.
75 matchset = enquire.mset(0, 10, relevant_docs)
77 # Display the results.
78 puts "#{matchset.matches_estimated()} results found."
79 puts "Matches 1-#{matchset.size}:\n"
81 matchset.matches.each {|m|
82 puts "#{m.rank + 1}: #{m.percent}% docid=#{m.docid} [#{m.document.data}]\n"
86 # Put the top 5 (at most) docs into the rset if rset is empty
87 if relevant_docs.empty?
88 matchset.matches[0..4].each {|match|
89 relevant_docs.add_document(match.docid())
93 # Get the suggested expand terms
94 expand_terms = enquire.eset(10, relevant_docs)
95 puts "#{expand_terms.size()} suggested additional terms:"
96 expand_terms.terms.each {|term|
97 puts " * Term \"#{term.name}\", weight #{term.weight}"