List of usage examples for org.apache.lucene.index IndexReader close
@Override public final synchronized void close() throws IOException
From source file:com.silverwrist.dynamo.index.IndexServiceImpl.java
License:Mozilla Public License
private final List doQuery(Query query, int offset, int count) throws IndexException { SubsetCollector subc = new SubsetCollector(offset, count + 1); List rc = null;/*www . j av a2 s . c o m*/ IndexReader irdr = null; IndexSearcher srch = null; try { // run that puppy! irdr = IndexReader.open(m_directory); srch = new IndexSearcher(irdr); if (query == null) visitAllDocuments(srch, subc); else srch.search(query, subc); rc = subc.outputItems(irdr); } // end try catch (IOException e) { // the query failed somehow - throw an error throw new IndexException(IndexServiceImpl.class, "IndexMessages", "query.fail", e); } // end catch finally { // make sure we close down OK try { // close the search and index reader if (srch != null) srch.close(); if (irdr != null) irdr.close(); } // end try catch (IOException e) { // shouldn't happen logger.warn("query(): error closing stuff", e); } // end catch } // end finally return rc; }
From source file:com.silverwrist.dynamo.index.IndexServiceImpl.java
License:Mozilla Public License
public boolean deleteItem(String item_namespace, String item_name, Object item) throws IndexException { // Create a Lucene Term matching the given document. Term term = new Term("id", createTag(item_namespace, item_name, item)); try { // Use an IndexReader to delete the appropriate document. IndexReader irdr = IndexReader.open(m_directory); int ndel = irdr.delete(term); irdr.close(); return (ndel > 0); } // end try/*from w ww. j av a2 s. c om*/ catch (IOException e) { // translate Lucene's IOException here IndexException ie = new IndexException(IndexServiceImpl.class, "IndexMessages", "deleteItem.fail", e); ie.setParameter(0, item_namespace); ie.setParameter(1, item_name); ie.setParameter(2, m_identity.toString()); throw ie; } // end catch }
From source file:com.sindicetech.siren.search.node.TestNodeFuzzyQuery.java
License:Open Source License
/** * MultiTermQuery provides (via attribute) information about which values * must be competitive to enter the priority queue. * * FuzzyQuery optimizes itself around this information, if the attribute * is not implemented correctly, there will be problems! *//*from ww w .ja v a 2s. co m*/ public void testTieBreaker() throws Exception { this.addDocument("<a123456>"); this.addDocument("<c123456>"); this.addDocument("<d123456>"); this.addDocument("<e123456>"); final Directory directory2 = newDirectory(); final RandomIndexWriter writer2 = newRandomIndexWriter(directory2, analyzer, codec); addDocument(writer2, "<a123456>"); addDocument(writer2, "<b123456>"); addDocument(writer2, "<b123456>"); addDocument(writer2, "<b123456>"); addDocument(writer2, "<c123456>"); addDocument(writer2, "<f123456>"); final IndexReader ir1 = writer.getReader(); final IndexReader ir2 = writer2.getReader(); final MultiReader mr = new MultiReader(ir1, ir2); final IndexSearcher searcher = newSearcher(mr); final FuzzyQuery fq = new FuzzyQuery(new Term(DEFAULT_TEST_FIELD, "z123456"), 1, 0, 2, false); final TopDocs docs = searcher.search(fq, 2); assertEquals(5, docs.totalHits); // 5 docs, from the a and b's mr.close(); ir2.close(); writer2.close(); directory2.close(); }
From source file:com.slieer.app.lecene3x.LuceneIndexAndSearchDemo.java
License:Apache License
/** * ???/*from w w w .j av a 2 s.c o m*/ * * @param args */ public static void main(String[] args) { // Lucene Document?? String fieldName = "text"; // String text = "IK Analyzer???????"; String text1 = "? (Chinese Word Segmentation) ???????????"; String text2 = "?????,,??,?"; // IKAnalyzer? Analyzer analyzer = new IKAnalyzer(true); Directory directory = null; IndexWriter iwriter = null; IndexReader ireader = null; IndexSearcher isearcher = null; try { // directory = new RAMDirectory(); // ?IndexWriterConfig IndexWriterConfig iwConfig = new IndexWriterConfig(Version.LUCENE_4_9, analyzer); iwConfig.setOpenMode(OpenMode.CREATE_OR_APPEND); iwriter = new IndexWriter(directory, iwConfig); // Document doc = new Document(); //document.add(new Field("content", content, Field.Store.YES, Field.Index.ANALYZED)); Field strField = new StringField("ID", "10000", Field.Store.YES); Field textFild = new StringField(fieldName, text, Field.Store.YES); //textFild.setBoost(2); doc.add(strField); doc.add(textFild); iwriter.addDocument(doc); doc = new Document(); strField = new StringField("ID", "10001", Field.Store.YES); textFild = new StringField(fieldName, text1, Field.Store.YES); //strField.setBoost(1); doc.add(strField); doc.add(textFild); iwriter.addDocument(doc); doc = new Document(); strField = new StringField("ID", "10002", Field.Store.YES); // textFild = new TextField(fieldName, text2, Field.Store.YES); textFild = new StringField(fieldName, text2, Field.Store.YES); //strField.setBoost(1); doc.add(strField); doc.add(textFild); iwriter.addDocument(doc); iwriter.close(); // ?********************************** // ? ireader = DirectoryReader.open(directory); isearcher = new IndexSearcher(ireader); String keyword = "?"; // QueryParser?Query QueryParser qp = new QueryParser(Version.LUCENE_4_9, fieldName, analyzer); qp.setDefaultOperator(QueryParser.AND_OPERATOR); Query query = qp.parse(keyword); System.out.println("Query = " + query); // ?5? TopDocs topDocs = isearcher.search(query, 5); System.out.println("" + topDocs.totalHits); // ScoreDoc[] scoreDocs = topDocs.scoreDocs; for (int i = 0; i < topDocs.totalHits; i++) { Document targetDoc = isearcher.doc(scoreDocs[i].doc); System.out.println("" + targetDoc.toString()); } } catch (CorruptIndexException e) { e.printStackTrace(); } catch (LockObtainFailedException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } finally { if (ireader != null) { try { ireader.close(); } catch (IOException e) { e.printStackTrace(); } } if (directory != null) { try { directory.close(); } catch (IOException e) { e.printStackTrace(); } } } }
From source file:com.slieer.app.lecene3x.SearchFiles.java
License:Apache License
/** Simple command-line based search demo. */ public static void main(String[] args) throws Exception { String usage = "Usage:\tjava org.apache.lucene.demo.SearchFiles [-index dir] [-field f] [-repeat n] [-queries file] [-query string] [-raw] [-paging hitsPerPage]\n\nSee http://lucene.apache.org/core/4_1_0/demo/ for details."; if (args.length > 0 && ("-h".equals(args[0]) || "-help".equals(args[0]))) { System.out.println(usage); System.exit(0);/*from www.j a v a 2s . c om*/ } String index = "index"; String field = "contents"; String queries = null; int repeat = 0; boolean raw = false; String queryString = null; int hitsPerPage = 10; for (int i = 0; i < args.length; i++) { if ("-index".equals(args[i])) { index = args[i + 1]; i++; } else if ("-field".equals(args[i])) { field = args[i + 1]; i++; } else if ("-queries".equals(args[i])) { queries = args[i + 1]; i++; } else if ("-query".equals(args[i])) { queryString = args[i + 1]; i++; } else if ("-repeat".equals(args[i])) { repeat = Integer.parseInt(args[i + 1]); i++; } else if ("-raw".equals(args[i])) { raw = true; } else if ("-paging".equals(args[i])) { hitsPerPage = Integer.parseInt(args[i + 1]); if (hitsPerPage <= 0) { System.err.println("There must be at least 1 hit per page."); System.exit(1); } i++; } } IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(index))); IndexSearcher searcher = new IndexSearcher(reader); // :Post-Release-Update-Version.LUCENE_XY: Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_4_9); BufferedReader in = null; if (queries != null) { in = new BufferedReader(new InputStreamReader(new FileInputStream(queries), StandardCharsets.UTF_8)); } else { in = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8)); } // :Post-Release-Update-Version.LUCENE_XY: QueryParser parser = new QueryParser(Version.LUCENE_4_9, field, analyzer); while (true) { if (queries == null && queryString == null) { // prompt the user System.out.println("Enter query: "); } String line = queryString != null ? queryString : in.readLine(); if (line == null || line.length() == -1) { break; } line = line.trim(); if (line.length() == 0) { break; } Query query = parser.parse(line); System.out.println("Searching for: " + query.toString(field)); if (repeat > 0) { // repeat & time as benchmark Date start = new Date(); for (int i = 0; i < repeat; i++) { searcher.search(query, null, 100); } Date end = new Date(); System.out.println("Time: " + (end.getTime() - start.getTime()) + "ms"); } doPagingSearch(in, searcher, query, hitsPerPage, raw, queries == null && queryString == null); if (queryString != null) { break; } } reader.close(); }
From source file:com.slieer.lucene.apachedemo.SearchFiles.java
License:Apache License
/** Simple command-line based search demo. */ public static void main(String[] args) throws Exception { String usage = "Usage:\tjava org.apache.lucene.demo.SearchFiles [-index dir] [-field f] [-repeat n] [-queries file] [-query string] [-raw] [-paging hitsPerPage]\n\nSee http://lucene.apache.org/core/4_1_0/demo/ for details."; if (args.length > 0 && ("-h".equals(args[0]) || "-help".equals(args[0]))) { System.out.println(usage); System.exit(0);/* w w w .java2s. c o m*/ } String index = "index"; String field = "contents"; String queries = null; int repeat = 0; boolean raw = false; String queryString = null; int hitsPerPage = 10; for (int i = 0; i < args.length; i++) { if ("-index".equals(args[i])) { index = args[i + 1]; i++; } else if ("-field".equals(args[i])) { field = args[i + 1]; i++; } else if ("-queries".equals(args[i])) { queries = args[i + 1]; i++; } else if ("-query".equals(args[i])) { queryString = args[i + 1]; i++; } else if ("-repeat".equals(args[i])) { repeat = Integer.parseInt(args[i + 1]); i++; } else if ("-raw".equals(args[i])) { raw = true; } else if ("-paging".equals(args[i])) { hitsPerPage = Integer.parseInt(args[i + 1]); if (hitsPerPage <= 0) { System.err.println("There must be at least 1 hit per page."); System.exit(1); } i++; } } IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(index))); IndexSearcher searcher = new IndexSearcher(reader); // :Post-Release-Update-Version.LUCENE_XY: Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_47); BufferedReader in = null; if (queries != null) { in = new BufferedReader(new InputStreamReader(new FileInputStream(queries), "UTF-8")); } else { in = new BufferedReader(new InputStreamReader(System.in, "UTF-8")); } // :Post-Release-Update-Version.LUCENE_XY: QueryParser parser = new QueryParser(Version.LUCENE_47, field, analyzer); while (true) { if (queries == null && queryString == null) { // prompt the user System.out.println("Enter query: "); } String line = queryString != null ? queryString : in.readLine(); if (line == null || line.length() == -1) { break; } line = line.trim(); if (line.length() == 0) { break; } Query query = parser.parse(line); System.out.println("Searching for: " + query.toString(field)); if (repeat > 0) { // repeat & time as benchmark Date start = new Date(); for (int i = 0; i < repeat; i++) { searcher.search(query, null, 100); } Date end = new Date(); System.out.println("Time: " + (end.getTime() - start.getTime()) + "ms"); } doPagingSearch(in, searcher, query, hitsPerPage, raw, queries == null && queryString == null); if (queryString != null) { break; } } reader.close(); }
From source file:com.soebes.supose.cli.SupoSECLI.java
License:Open Source License
/** * The search command./* w w w.j a v a 2 s . co m*/ * * @param searchCommand */ private void runSearch(SearchCommand searchCommand) { LOGGER.info("Searching started..."); String indexDirectory = searchCommand.getIndexName(); String queryLine = searchCommand.getQuery(); boolean xml = searchCommand.isXML(); List<FieldNames> cliFields = searchCommand.getFields(); SearchRepository searchRepository = new SearchRepository(indexDirectory); List<ResultEntry> result = searchRepository.getResult(queryLine); if (xml) { XStream xstream = new XStream(); xstream.alias("entry", ResultEntry.class); System.out.println(xstream.toXML(result)); } else { System.out.println("Query: '" + queryLine + "'"); if (cliFields.size() > 0) { for (int i = 0; i < cliFields.size(); i++) { System.out.print("Field[" + i + "]=" + cliFields.get(i) + " "); } } else { cliFields = new ArrayList<FieldNames>(); // If nothings is given on command line we have to define // default fields which will be printed cliFields.add(FieldNames.REVISION); cliFields.add(FieldNames.FILENAME); cliFields.add(FieldNames.PATH); cliFields.add(FieldNames.KIND); } if (result == null) { System.out.println("Somethings has gone wrong. Check the log file output!"); return; } System.out.println("Total Hits: " + result.size()); long count = 1; for (ResultEntry item : result) { System.out.printf("%6d: ", count); for (FieldNames fn : cliFields) { if (fn.equals(FieldNames.PROPERTIES)) { // Properties will be put into separate lines System.out.println(""); Map<String, String> properties = item.getProperties(); for (Map.Entry<String, String> prop : properties.entrySet()) { System.out.println(" --> K:" + prop.getKey() + " V:" + prop.getValue()); } } else { Object attribute = searchRepository.callGetterByName(item, fn.getValue()); System.out.print(fn.name() + ":" + attribute + " "); } } System.out.println(""); count++; } } IndexReader reader = searchRepository.getReader(); try { reader.close(); } catch (IOException e) { LOGGER.error("Error during closing of the index happened: ", e); } }
From source file:com.soebes.supose.core.scan.SearchRepositoryGetQueryTest.java
License:Open Source License
@AfterClass public void afterClass() throws IOException { IndexReader reader = searchRepository.getReader(); reader.close(); }
From source file:com.stimulus.archiva.search.StandardSearch.java
License:Open Source License
public long getTotalMessageCount(Volume volume) throws MessageSearchException { if (volume == null) throw new MessageSearchException("assertion failure: null volume", logger); //logger.debug("get total no emails {indexpath='"+volume.getIndexPath()+"'}"); int count = 0; File indexDir = new File(volume.getIndexPath()); if (!indexDir.exists()) return 0; IndexReader indexReader = null; try {/*from ww w .j a va 2s . c o m*/ indexReader = IndexReader.open(indexDir); count += indexReader.numDocs(); indexReader.close(); } catch (IOException e) { logger.debug("failed to open index to calculate total email count", e); //throw new MessageSearchException("failed to open index to calculate total email count",e,logger); } return count; }
From source file:com.sun.javaee.blueprints.carstore.search.UpdateIndex.java
License:Berkeley License
public static Document deleteIndex(String indexFile, String sxDocId) throws IOException { // get document to update, so data can be added SearchIndex si = new SearchIndex(); si.query(indexFile, sxDocId, "uid"); Hits hits = si.getHitsNative();//from ww w . ja v a 2s . c o m // should only have one return if (hits.length() > 1) { // exception, should only be one throw new IllegalStateException("Should only have one document in index with uid=" + sxDocId); } Document doc = (Document) hits.doc(0); if (bDebug) System.out.println("HAVE DOC " + doc); // Read index and delete targeted doc through a term IndexReader reader = IndexReader.open(indexFile); // delete document by term int delcnt = reader.deleteDocuments(new Term("uid", sxDocId)); if (bDebug) { System.out.println("return Number of items deleted:" + delcnt); int deleted = 0; for (int ii = 0; ii < reader.numDocs(); ii++) { if (reader.isDeleted(ii)) { deleted++; } } if (bDebug) System.out.println("Number of deleted items in the whole index:" + deleted); } reader.close(); return doc; }