SampleCode: NumberValueRange_example.php

File NumberValueRange_example.php, 2.2 KB (added by Olly Betts, 16 years ago)

Example showing how to use NumberValueRangeProcessor to perform numeric range searches in PHP

Line 
1<?php
2if (php_sapi_name() != "cli") {
3 print "This example script is written to run under the command line ('cli') version of\n";
4 print "the PHP interpreter, but you're using the '".php_sapi_name()."' version\n";
5 exit(1);
6}
7
8include "xapian.php";
9
10if ($argc != 2) {
11 print "Usage: {$argv[0]} PATH_TO_DATABASE\n";
12 exit(1);
13}
14
15try {
16 // Open the database for update, creating a new database if necessary.
17 $database = new XapianWritableDatabase($argv[1], Xapian::DB_CREATE_OR_OVERWRITE);
18
19 // add a document with a term and a timestamp value
20 $doc = new XapianDocument();
21 $doc->add_term("foo");
22 $doc->add_value(1, Xapian::sortable_serialise(1000000000));
23 $database->add_document($doc);
24
25 // add another: same term, different timestamp value
26 $doc = new XapianDocument();
27 $doc->add_term("foo");
28 $doc->add_value(1, Xapian::sortable_serialise(2000000000));
29 $database->add_document($doc);
30
31 // Set the database handle to Null to ensure that it gets closed
32 // down cleanly or unflushed changes may be lost.
33 $database = Null;
34
35 // open database for reading
36 $database = new XapianDatabase($argv[1]);
37 $enquire = new XapianEnquire($database);
38
39 // example 1 using a query processor
40 $qp = new XapianQueryParser();
41 $qp->set_database($database);
42 $datenumproc = new XapianNumberValueRangeProcessor(1);
43 $qp->add_valuerangeprocessor($datenumproc);
44
45 // without range: get both docs
46 $query = $qp->parse_query("foo");
47 $enquire->set_query($query);
48 print $enquire->get_mset(0, 10)->size();
49 print "\n";
50
51 // with range: get first doc
52 $query = $qp->parse_query("foo 1000000000..1500000000");
53 $enquire->set_query($query);
54 print $enquire->get_mset(0, 10)->size();
55 print "\n";
56
57 // example 2 - direct query construction (get first doc)
58 $query = new XapianQuery(XapianQuery::OP_VALUE_RANGE,
59 1,
60 Xapian::sortable_serialise(1000000000),
61 Xapian::sortable_serialise(1500000000));
62 $enquire->set_query($query);
63 print $enquire->get_mset(0, 10)->size();
64 print "\n";
65
66} catch (Exception $e) {
67 print $e->getMessage() . "\n";
68 exit(1);
69}
70?>