Package org.apache.lucene.search

Examples of org.apache.lucene.search.Searcher


     *               is the what is being searched for
     * @return Hits, if no hits then null.
     */
    public SearchResults search(String searchString)
    {
        Searcher searcher = null;
        Hits hits = null;
       
        try
        {
            searcher = new IndexSearcher(rootDir.getPath());
        }
        catch (IOException e)
        {
            logger.error("Failed to create index search using path " + rootDir.getPath());
            return null;
        }
       
        Analyzer analyzer = newAnalyzer();
       
        String[] searchFields = {ParsedObject.FIELDNAME_CONTENT, ParsedObject.FIELDNAME_DESCRIPTION, ParsedObject.FIELDNAME_FIELDS,
                           ParsedObject.FIELDNAME_KEY, ParsedObject.FIELDNAME_KEYWORDS, ParsedObject.FIELDNAME_LANGUAGE,
                           ParsedObject.FIELDNAME_SCORE, ParsedObject.FIELDNAME_TITLE, ParsedObject.FIELDNAME_TYPE,
                           ParsedObject.FIELDNAME_URL, ParsedObject.FIELDNAME_CLASSNAME};
                           
        Query query= null;
        try
        {
            query = MultiFieldQueryParser.parse(searchString, searchFields, analyzer);
//          Query query = QueryParser.parse(searchString, ParsedObject.FIELDNAME_CONTENT, analyzer);
        }
        catch (ParseException e)
        {
            logger.info("Failed to parse query " + searchString);
            return null;
        }
       
        try
        {
            hits = searcher.search(query);
        }
        catch (IOException e)
        {
           logger.error("Error while peforming search.", e);
           return null;
        }

        // Copy hits to the result list
        int hitCount = hits.length();
        Document doc = null;
        SearchResults results = new SearchResults(hitCount);
        for (int counter = 0; counter < hitCount; counter++)
        {           
            ParsedObject result = new BaseParsedObject();
            try
            {
                doc = hits.doc(counter);
                addFieldsToParsedObject(doc, result);
               
                result.setScore(hits.score(counter));
                Field type = doc.getField(ParsedObject.FIELDNAME_TYPE);
                if(type != null)
                {
                    result.setType(type.stringValue());
                }
               
                Field key = doc.getField(ParsedObject.FIELDNAME_KEY);
                if(key != null)
                {
                    result.setKey(key.stringValue());
                }
               
                Field description = doc.getField(ParsedObject.FIELDNAME_DESCRIPTION);
                if(description != null)
                {
                    result.setDescription(description.stringValue());
                }
               
                Field title = doc.getField(ParsedObject.FIELDNAME_TITLE);
                if(title != null)
                {
                    result.setTitle(title.stringValue());
                }
               
                Field content = doc.getField(ParsedObject.FIELDNAME_CONTENT);
                if(content != null)
                {
                    result.setContent(content.stringValue());
                }
               
                Field language = doc.getField(ParsedObject.FIELDNAME_LANGUAGE);
                if (language != null)
                {
                  result.setLanguage(language.stringValue());
                }
               
                Field classname = doc.getField(ParsedObject.FIELDNAME_CLASSNAME);
                if (classname != null)
                {
                  result.setClassName(classname.stringValue());
                }
               
                Field url = doc.getField(ParsedObject.FIELDNAME_URL);
                if (url != null)
                {
                    result.setURL(new URL(url.stringValue()));
                }
               
                results.add(counter, result);
            }
            catch (Exception ioe)
            {
                logger.error("Exception", ioe);
            }
        }

        if (searcher != null)
        {
            try
            {
                searcher.close();
            }
            catch (IOException ioe)
            {
                logger.error("Closing Searcher", ioe);
            }
View Full Code Here


            }
        }

        try
        {
            Searcher searcher = null;
            searcher = new IndexSearcher(rootDir.getPath());
            searcher.close();
        }
        catch (Exception e)
        {
            try
            {
View Full Code Here

     *               is the what is being searched for
     * @return Hits, if no hits then null.
     */
    public SearchResults search(String searchString)
    {
        Searcher searcher = null;
        Hits hits = null;
        try
        {
            searcher = new IndexSearcher(rootDir.getPath());
            Analyzer analyzer = new StandardAnalyzer();
            Query query = QueryParser.parse(searchString, ParsedObject.FIELDNAME_CONTENT, analyzer);
            hits = searcher.search(query);
        }
        catch (Exception e)
        {
            logger.error("Exception", e);
        }

        // Copy hits to the result list
        int hitCount = hits.length();
        Document doc = null;
        SearchResults results = new SearchResults(hitCount);
        for (int counter = 0; counter < hitCount; counter++)
        {           
            ParsedObject result = new BaseParsedObject();
            try
            {
                doc = hits.doc(counter);
                result.setScore(hits.score(counter));
                result.setType(doc.getField(ParsedObject.FIELDNAME_TYPE).stringValue());
                result.setKey(doc.getField(ParsedObject.FIELDNAME_KEY).stringValue());
                result.setDescription(doc.getField(ParsedObject.FIELDNAME_DESCRIPTION).stringValue());
                result.setTitle(doc.getField(ParsedObject.FIELDNAME_TITLE).stringValue());
                Field url = doc.getField(ParsedObject.FIELDNAME_URL);
                if (url != null)
                {
                    result.setURL(new URL(url.stringValue()));
                }               
                results.add(counter, result);
            }
            catch (Exception ioe)
            {
                logger.error("Exception", ioe);
            }
            result = null;
        }

        if (searcher != null)
        {
            try
            {
                searcher.close();
            }
            catch (IOException ioe)
            {
                logger.error("Closing Searcher", ioe);
            }
View Full Code Here

    private static String[] queryImpl( String aLanguageStr, String aIndexStr, String aQueryStr,
      boolean bCaptionOnly, Object[] aScoreOutArray ) throws Exception
    {
      IndexReader reader = IndexReader.open( aIndexStr );
      Searcher searcher = new IndexSearcher( reader );
            Analyzer analyzer = aLanguageStr.equals("ja") ? (Analyzer)new CJKAnalyzer() : (Analyzer)new StandardAnalyzer();

      String aField;
      if( bCaptionOnly )
        aField = "caption";
      else
        aField = "content";

      Query aQuery;
      if( aQueryStr.endsWith( "*" ) )
        aQuery = new WildcardQuery( new Term( aField, aQueryStr ) );
      else
        aQuery = new TermQuery( new Term( aField, aQueryStr ) );

      // Perform search
      Hits aHits = searcher.search( aQuery );
      int nHitCount = aHits.length();

      String aDocs[] = new String[nHitCount]
      float aScores[] = null;
      aScores = new float[nHitCount];
View Full Code Here

                          Field.Store.NO, Field.Index.ANALYZED));
      writer.addDocument(doc);
    }
    writer.optimize();
    writer.close();
    Searcher searcher = new IndexSearcher(indexStore, true);

    Sort sort = new Sort();
    Query queryX = new TermQuery(new Term ("contents", "x"));
    Query queryY = new TermQuery(new Term ("contents", "y"));
   
View Full Code Here

    IndexReader reader = IndexReader.open(index);

    if (normsField != null)
      reader = new OneNormsReader(reader, normsField);

    Searcher searcher = new IndexSearcher(reader);
    Analyzer analyzer = new StandardAnalyzer();

    BufferedReader in = null;
    if (queries != null) {
      in = new BufferedReader(new FileReader(queries));
    } else {
      in = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
    }
      QueryParser parser = new QueryParser(field, analyzer);
    while (true) {
      if (queries == null)                        // prompt the user
        System.out.print("Query: ");

      String line = in.readLine();

      if (line == null || line.length() == -1)
        break;

      Query query = parser.parse(line);
      System.out.println("Searching for: " + query.toString(field));

      Hits hits = searcher.search(query);
     
      if (repeat > 0) {                           // repeat & time as benchmark
        Date start = new Date();
        for (int i = 0; i < repeat; i++) {
          hits = searcher.search(query);
        }
        Date end = new Date();
        System.out.println("Time: "+(end.getTime()-start.getTime())+"ms");
      }
View Full Code Here

        Searcher[] searchers = new Searcher[2];
        // VITAL STEP:adding the searcher for the empty index first, before the searcher for the populated index
        searchers[0] = new IndexSearcher(indexStoreB);
        searchers[1] = new IndexSearcher(indexStoreA);
        // creating the multiSearcher
        Searcher mSearcher = getMultiSearcherInstance(searchers);
        // performing the search
        Hits hits = mSearcher.search(query);

        assertEquals(3, hits.length());

        // iterating over the hit documents
        for (int i = 0; i < hits.length(); i++) {
            Document d = hits.doc(i);
        }
        mSearcher.close();


        //--------------------------------------------------------------------
        // scenario 2
        //--------------------------------------------------------------------

        // adding one document to the empty index
        writerB = new IndexWriter(indexStoreB, new StandardAnalyzer(), false);
        writerB.addDocument(lDoc);
        writerB.optimize();
        writerB.close();

        // building the searchables
        Searcher[] searchers2 = new Searcher[2];
        // VITAL STEP:adding the searcher for the empty index first, before the searcher for the populated index
        searchers2[0] = new IndexSearcher(indexStoreB);
        searchers2[1] = new IndexSearcher(indexStoreA);
        // creating the mulitSearcher
        MultiSearcher mSearcher2 = getMultiSearcherInstance(searchers2);
        // performing the same search
        Hits hits2 = mSearcher2.search(query);

        assertEquals(4, hits2.length());

        // iterating over the hit documents
        for (int i = 0; i < hits2.length(); i++) {
            // no exception should happen at this point
            Document d = hits2.doc(i);
        }
        mSearcher2.close();

        // test the subSearcher() method:
        Query subSearcherQuery = parser.parse("id:doc1");
        hits2 = mSearcher2.search(subSearcherQuery);
        assertEquals(2, hits2.length());
        assertEquals(0, mSearcher2.subSearcher(hits2.id(0)));   // hit from searchers2[0]
        assertEquals(1, mSearcher2.subSearcher(hits2.id(1)));   // hit from searchers2[1]
        subSearcherQuery = parser.parse("id:doc2");
        hits2 = mSearcher2.search(subSearcherQuery);
        assertEquals(1, hits2.length());
        assertEquals(1, mSearcher2.subSearcher(hits2.id(0)));   // hit from searchers2[1]

        //--------------------------------------------------------------------
        // scenario 3
        //--------------------------------------------------------------------

        // deleting the document just added, this will cause a different exception to take place
        Term term = new Term("id", "doc1");
        IndexReader readerB = IndexReader.open(indexStoreB);
        readerB.deleteDocuments(term);
        readerB.close();

        // optimizing the index with the writer
        writerB = new IndexWriter(indexStoreB, new StandardAnalyzer(), false);
        writerB.optimize();
        writerB.close();

        // building the searchables
        Searcher[] searchers3 = new Searcher[2];

        searchers3[0] = new IndexSearcher(indexStoreB);
        searchers3[1] = new IndexSearcher(indexStoreA);
        // creating the mulitSearcher
        Searcher mSearcher3 = getMultiSearcherInstance(searchers3);
        // performing the same search
        Hits hits3 = mSearcher3.search(query);

        assertEquals(3, hits3.length());

        // iterating over the hit documents
        for (int i = 0; i < hits3.length(); i++) {
            Document d = hits3.doc(i);
        }
        mSearcher3.close();
    }
View Full Code Here

        initIndex(ramDirectory2, nDocs, true, "x"); // documents with two tokens "doc0" and "x", "doc1" and x, etc...
       
        indexSearcher1=new IndexSearcher(ramDirectory1);
        indexSearcher2=new IndexSearcher(ramDirectory2);
       
        Searcher searcher=getMultiSearcherInstance(new Searcher[] { indexSearcher1, indexSearcher2 });
       
        hits=searcher.search(query);
       
        assertEquals(message, 2, hits.length());
       
        // The scores should be the same (within reason)
        assertEquals(message, scores[0], hits.score(0), 1e-6); // This will a document from ramDirectory1
        assertEquals(message, scores[1], hits.score(1), 1e-6); // This will a document from ramDirectory2
       
       
       
        // Adding a Sort.RELEVANCE object should not change anything
        hits=searcher.search(query, Sort.RELEVANCE);
       
        assertEquals(message, 2, hits.length());
       
        assertEquals(message, scores[0], hits.score(0), 1e-6); // This will a document from ramDirectory1
        assertEquals(message, scores[1], hits.score(1), 1e-6); // This will a document from ramDirectory2
       
        searcher.close();
       
        ramDirectory1.close();
        ramDirectory2.close();
    }
View Full Code Here

    private static String[] queryImpl( String aLanguageStr, String aIndexStr, String aQueryStr,
      boolean bCaptionOnly, Object[] aScoreOutArray ) throws Exception
    {
      File aIndexFile = new File( aIndexStr );
      IndexReader reader = IndexReader.open( NIOFSDirectory.open( aIndexFile ), true );
      Searcher searcher = new IndexSearcher( reader );
      Analyzer analyzer = aLanguageStr.equals("ja") ? (Analyzer)new CJKAnalyzer(Version.LUCENE_29) : (Analyzer)new StandardAnalyzer(Version.LUCENE_29);

      String aField;
      if( bCaptionOnly )
        aField = "caption";
      else
        aField = "content";

      Query aQuery;
      if( aQueryStr.endsWith( "*" ) )
        aQuery = new WildcardQuery( new Term( aField, aQueryStr ) );
      else
        aQuery = new TermQuery( new Term( aField, aQueryStr ) );

      // Perform search
      TopDocs aHits = searcher.search( aQuery, 100 );
      int nHitCount = aHits.scoreDocs.length;

      String aDocs[] = new String[nHitCount]
      float aScores[] = null;
      aScores = new float[nHitCount];
      for( int iHit = 0 ; iHit < nHitCount ; iHit++ )
      {
        ScoreDoc aDoc = aHits.scoreDocs[iHit];
        String aPath = searcher.doc(aDoc.doc).get( "path" );
        aDocs[iHit] = ( aPath != null ) ? aPath : "";
        aScores[iHit] = aDoc.score;
      }
      aScoreOutArray[0] = aScores;

View Full Code Here

    {
        IBasicResultSet result = new BasicResultSetImpl (false);
       
        try
        {
            Searcher searcher = new IndexSearcher(indexPath);
            Analyzer analyzer = new StandardAnalyzer();
           
            Query query = QueryParser.parse(searchedText, "contents", analyzer);
            Hits hits = searcher.search (query);
            int noOfHits = hits.length();
           
            for (int i = 0; i < noOfHits; i++)
            {
                Document doc = hits.doc(i);
View Full Code Here

TOP

Related Classes of org.apache.lucene.search.Searcher

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.