Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve the Field that "hit" in Lucene

Tags:

java

lucene

Maybe I'm really missing something.

I have indexed a bunch of key/value pairs in Lucene (v4.1 if it matters). Say I have key1=value1 and key2=value2, e.g. as read from a properties file.

They get indexed both as specific fields and into a catchall "ALL" field, e.g.

new Field("key1", "value1", aFieldTypeMimickingKeywords);
new Field("key2", "value2", aFieldTypeMimickingKeywords);
new Field("ALL", "key1=value1", aFieldTypeMimickingKeywords);
new Field("ALL", "key2=value2", aFieldTypeMimickingKeywords);
// then get added to the Document of course...

I can then do a wildcard search, using

new WildcardQuery(new Term("ALL", "*alue1"));

and it will find the hit.

But, it would be nice to get more info, like "what was complete value (e.g. "key1=value1") that goes with that hit?".

The best I can figure out it to get the Document, then get the list of IndexableFields, then loop over all of them and see if the field.stringValue().contains("alue1"). (I can look at the data structures in the debugger and all the info is there)

This seems completely insane cause isn't that what Lucene just did? Shouldn't the Hit information return some of the Fields?

Is Lucene missing what seems like "obvious" functionality? Google and starting at the APIs hasn't revealed anything straightforward, but I feel like I must be searching on the wrong stuff.

like image 627
user949300 Avatar asked Mar 02 '13 21:03

user949300


1 Answers

You might want to try with IndexSearcher.explain() method. Once you get the ID of the matching document, prepare a query for each field (using the same search keywords) and invoke Explanation.isMatch() for each query: the ones that yield true will give you the matched field. Example:

for (String field: fields){
    Query query = new WildcardQuery(new Term(field, "*alue1"));
    Explanation ex = searcher.explain(query, docID);
    if (ex.isMatch()){
        //Your query matched field
    }
}
like image 107
Emanuele Bezzi Avatar answered Oct 11 '22 23:10

Emanuele Bezzi