Preface:
Lucene includes a whole family of queries based on SpanQuery, loosely mirroring the normal Lucene Query classes. A span in this context is a starting and ending token position in a field. Recall from section 4.2.1 that tokens emitted during the analysis process include a position from the previous token. This position information, in conjunction with the new SpanQuery subclasses, allows for even more query discrimination and sophistication, such as all documents where “President Obama” is near “health care reform.”
Using the query types we’ve discussed thus far, it isn’t possible to formulate such a position-aware query. You could get close with something like "president obama" AND "health care reform", but these phrases may be too distant from one another within the document to be relevant for our searching purposes. In typical applications,SpanQuerys are used to provide richer, more expressive position-aware functionality than PhraseQuery. They’re also commonly used in conjunction with payloads, covered in section 6.5, to enable access to the payloads created during indexing.
While searching, span queries track more than the documents that match: the individual spans, perhaps more than one per field, are also tracked. Contrasting withTermQuery, which simply matches documents, SpanTermQuery matches exactly the same documents but also keeps track of the positions of every term occurrence that matches. Generally this is more compute-intensive. For example, when TermQuery finds a document containing its term, it records that document as a match and immediately moves on, whereas SpanTermQuery must enumerate all the occurrences of that term within the document.
There are six subclasses of the base SpanQuery, shown in table 5.1. We’ll discuss these SpanQuery types with a simple example, shown in listing 5.8: we’ll index two documents, one with the phrase “the quick brown fox jumps over the lazy dog” and the other with the similar phrase “the quick red fox jumps over the sleepy cat.” We’ll create a separate SpanTermQuery for each of the terms in these documents, as well as three helper assert methods. Finally, we’ll create the different types of span queries to illustrate their functions.
- Listing 5.8 SpanQuery demonstration infrastructure
Building block of spanning, SpanTermQuery:
Span queries need an initial leverage point, and SpanTermQuery is just that. Internally, a SpanQuery keeps track of its matches: a series of start/end positions for each matching document. By itself, a SpanTermQuery matches documents just like TermQuery does, but it also keeps track of position of the same terms that appear within each document. Generally you’d never use this query by itself (you’d use TermQuery instead); you only use it as inputs to the other SpanQuery classes. Figure 5.1 illustrates the SpanTermQuery matches for this code below:
The brown SpanTermQuery was created in setUp() because it will be used in other tests that follow. We developed a method, dumpSpans, to visualize spans. ThedumpSpans method uses lower-level SpanQuery APIs to navigate the spans; this lower-level API probably isn’t of much interest to you other than for diagnostic purposes, so we don’t elaborate further. Each SpanQuery subclass sports a useful toString() for diagnostic purposes, which dumpSpans uses, as seen in listing 5.9.
- Listing 5.9 dumpSpans method, used to see all spans matched by any SpanQuery
The output of
dumpSpans(brown) is:
More interesting is the dumpSpans output from a SpanTermQuery for "the":
Not only were both documents matched, but also each document had two span matches highlighted by the brackets. The basic SpanTermQuery is used as a building block of the other SpanQuery types. Let’s see how to match only documents where the terms of interest occur in the beginning of the field.
Finding spans at the beginning of a field:
To query for spans that occur within the first specific number of positions of a field, use SpanFirstQuery. Figure 5.2 illustrates a SpanFirstQuery case as below:
No matches are found in the first query because the range of 2 is too short to find brown, but the range of 3 is just long enough to cause a match in the second query (see figure 5.2). Any SpanQuery can be used within a SpanFirstQuery, with matches for spans that have an ending position in the first specified number (2 and 3 in this case) of positions. The output of testSpanFirstQuery() as below:
Supplement:
* Ch5. Advanced search techniques - Span queries (1)
* Ch5. Advanced search techniques - Span queries (2)
Lucene includes a whole family of queries based on SpanQuery, loosely mirroring the normal Lucene Query classes. A span in this context is a starting and ending token position in a field. Recall from section 4.2.1 that tokens emitted during the analysis process include a position from the previous token. This position information, in conjunction with the new SpanQuery subclasses, allows for even more query discrimination and sophistication, such as all documents where “President Obama” is near “health care reform.”
Using the query types we’ve discussed thus far, it isn’t possible to formulate such a position-aware query. You could get close with something like "president obama" AND "health care reform", but these phrases may be too distant from one another within the document to be relevant for our searching purposes. In typical applications,SpanQuerys are used to provide richer, more expressive position-aware functionality than PhraseQuery. They’re also commonly used in conjunction with payloads, covered in section 6.5, to enable access to the payloads created during indexing.
While searching, span queries track more than the documents that match: the individual spans, perhaps more than one per field, are also tracked. Contrasting withTermQuery, which simply matches documents, SpanTermQuery matches exactly the same documents but also keeps track of the positions of every term occurrence that matches. Generally this is more compute-intensive. For example, when TermQuery finds a document containing its term, it records that document as a match and immediately moves on, whereas SpanTermQuery must enumerate all the occurrences of that term within the document.
There are six subclasses of the base SpanQuery, shown in table 5.1. We’ll discuss these SpanQuery types with a simple example, shown in listing 5.8: we’ll index two documents, one with the phrase “the quick brown fox jumps over the lazy dog” and the other with the similar phrase “the quick red fox jumps over the sleepy cat.” We’ll create a separate SpanTermQuery for each of the terms in these documents, as well as three helper assert methods. Finally, we’ll create the different types of span queries to illustrate their functions.
- Listing 5.8 SpanQuery demonstration infrastructure
- package ch5;
- import junit.framework.TestCase;
- import org.apache.lucene.analysis.SimpleAnalyzer;
- import org.apache.lucene.document.Document;
- import org.apache.lucene.document.Field;
- import org.apache.lucene.index.IndexReader;
- import org.apache.lucene.index.IndexWriter;
- import org.apache.lucene.index.IndexWriterConfig;
- import org.apache.lucene.index.Term;
- import org.apache.lucene.search.IndexSearcher;
- import org.apache.lucene.search.Query;
- import org.apache.lucene.search.TopDocs;
- import org.apache.lucene.search.spans.SpanTermQuery;
- import org.apache.lucene.store.Directory;
- import org.apache.lucene.store.RAMDirectory;
- import org.apache.lucene.util.Version;
- public class SpanQueryTest extends TestCase {
- private IndexSearcher searcher;
- private SimpleAnalyzer analyzer = null;
- public static Version LUCENE_VERSION = Version.LUCENE_30;
- private SpanTermQuery quick;
- private SpanTermQuery brown;
- private SpanTermQuery red;
- private SpanTermQuery fox;
- private SpanTermQuery lazy;
- private SpanTermQuery sleepy;
- private SpanTermQuery dog;
- private SpanTermQuery cat;
- protected void setUp() throws Exception {
- Directory directory = new RAMDirectory();
- analyzer = new SimpleAnalyzer(LUCENE_VERSION);
- IndexWriterConfig iwConfig = new IndexWriterConfig(LUCENE_VERSION, analyzer);
- IndexWriter writer = new IndexWriter(directory, iwConfig);
- Document doc = new Document();
- doc.add(new Field("f", "the quick brown fox jumps over the lazy dog",
- Field.Store.YES, Field.Index.ANALYZED));
- writer.addDocument(doc);
- doc = new Document();
- doc.add(new Field("f", "the quick red fox jumps over the sleepy cat",
- Field.Store.YES, Field.Index.ANALYZED));
- writer.addDocument(doc);
- writer.close();
- IndexReader reader = IndexReader.open(directory);
- searcher = new IndexSearcher(reader);
- quick = new SpanTermQuery(new Term("f", "quick"));
- brown = new SpanTermQuery(new Term("f", "brown"));
- red = new SpanTermQuery(new Term("f", "red"));
- fox = new SpanTermQuery(new Term("f", "fox"));
- lazy = new SpanTermQuery(new Term("f", "lazy"));
- sleepy = new SpanTermQuery(new Term("f", "sleepy"));
- dog = new SpanTermQuery(new Term("f", "dog"));
- cat = new SpanTermQuery(new Term("f", "cat"));
- }
- @Override
- protected void tearDown() throws Exception
- {
- searcher.close();
- }
- private void assertOnlyBrownFox(Query query) throws Exception {
- TopDocs hits = searcher.search(query, 10);
- assertEquals(1, hits.totalHits);
- assertEquals("wrong doc", 0, hits.scoreDocs[0].doc);
- }
- private void assertBothFoxes(Query query) throws Exception {
- TopDocs hits = searcher.search(query, 10);
- assertEquals(2, hits.totalHits);
- }
- private void assertNoMatches(Query query) throws Exception {
- TopDocs hits = searcher.search(query, 10);
- assertEquals(0, hits.totalHits);
- }
- }
Span queries need an initial leverage point, and SpanTermQuery is just that. Internally, a SpanQuery keeps track of its matches: a series of start/end positions for each matching document. By itself, a SpanTermQuery matches documents just like TermQuery does, but it also keeps track of position of the same terms that appear within each document. Generally you’d never use this query by itself (you’d use TermQuery instead); you only use it as inputs to the other SpanQuery classes. Figure 5.1 illustrates the SpanTermQuery matches for this code below:
- public void testSpanTermQuery() throws Exception {
- assertOnlyBrownFox(brown);
- dumpSpans(brown);
- }
The brown SpanTermQuery was created in setUp() because it will be used in other tests that follow. We developed a method, dumpSpans, to visualize spans. ThedumpSpans method uses lower-level SpanQuery APIs to navigate the spans; this lower-level API probably isn’t of much interest to you other than for diagnostic purposes, so we don’t elaborate further. Each SpanQuery subclass sports a useful toString() for diagnostic purposes, which dumpSpans uses, as seen in listing 5.9.
- Listing 5.9 dumpSpans method, used to see all spans matched by any SpanQuery
- private void dumpSpans(SpanQuery query) throws IOException {
- Spans spans = query.getSpans(searcher.getIndexReader());
- System.out.println(query + ":");
- int numSpans = 0;
- TopDocs hits = searcher.search(query, 10);
- float[] scores = new float[2];
- for (ScoreDoc sd : hits.scoreDocs) {
- scores[sd.doc] = sd.score;
- }
- while (spans.next()) {
- numSpans++;
- int id = spans.doc();
- Document doc = searcher.getIndexReader().document(id);
- TokenStream stream = analyzer.tokenStream("contents",
- new StringReader(doc.get("f")));
- TermAttribute term = stream.addAttribute(TermAttribute.class);
- StringBuilder buffer = new StringBuilder();
- buffer.append(" ");
- int i = 0;
- while (stream.incrementToken()) {
- if (i == spans.start()) {
- buffer.append("<");
- }
- buffer.append(term.term());
- if (i + 1 == spans.end()) {
- buffer.append(">");
- }
- buffer.append(" ");
- i++;
- }
- buffer.append("(").append(scores[id]).append(") ");
- System.out.println(buffer);
- }
- if (numSpans == 0) {
- System.out.println(" No spans");
- }
- System.out.println();
- }
More interesting is the dumpSpans output from a SpanTermQuery for "the":
Not only were both documents matched, but also each document had two span matches highlighted by the brackets. The basic SpanTermQuery is used as a building block of the other SpanQuery types. Let’s see how to match only documents where the terms of interest occur in the beginning of the field.
Finding spans at the beginning of a field:
To query for spans that occur within the first specific number of positions of a field, use SpanFirstQuery. Figure 5.2 illustrates a SpanFirstQuery case as below:
- public void testSpanFirstQuery() throws Exception {
- SpanFirstQuery sfq = new SpanFirstQuery(brown, 2);
- assertNoMatches(sfq);
- dumpSpans(sfq);
- sfq = new SpanFirstQuery(brown, 3);
- dumpSpans(sfq);
- assertOnlyBrownFox(sfq);
- }
No matches are found in the first query because the range of 2 is too short to find brown, but the range of 3 is just long enough to cause a match in the second query (see figure 5.2). Any SpanQuery can be used within a SpanFirstQuery, with matches for spans that have an ending position in the first specified number (2 and 3 in this case) of positions. The output of testSpanFirstQuery() as below:
Supplement:
* Ch5. Advanced search techniques - Span queries (1)
* Ch5. Advanced search techniques - Span queries (2)
This message was edited 17 times. Last update was at 14/05/2013 10:26:48
沒有留言:
張貼留言