16-Aug-05 (Created: 16-Aug-05) | More in 'Lucene'

lucene: How to locate a lucene document using a compound primary key


    public Document searchForDocument(String appType, String id)
    throws IOException
    {
        Searcher s = null;
        try
        {
            Term appTerm = new Term("app",appType);
            TermQuery appTermQuery = new TermQuery(appTerm);
            
            Term idTerm = new Term("id",id);
            TermQuery idTermQuery = new TermQuery(idTerm);
            
            BooleanQuery andQuery = new BooleanQuery();
            andQuery.add(appTermQuery,true,false);
            andQuery.add(idTermQuery,true,false);
            
            s = getIndexSearcher(); 
            Hits hits = s.search(andQuery);
            if (hits.length() == 0)
            {
                Log.log("warn: Sorry not found");
                return null;
            }
            if (hits.length() > 1)
            {
                throw new RuntimeException("Too many hits.");
            }
            return hits.doc(0);
        }
        finally
        {
            if (s != null) s.close();
        }
    }//eof-function