List of usage examples for org.apache.lucene.search Sort Sort
public Sort(SortField... fields)
From source file:com.b2international.snowowl.snomed.api.impl.ClassificationRunIndex.java
License:Apache License
public void trimIndex(int maximumResultsToKeep) throws IOException { final Query query = Fields.newQuery().field(FIELD_CLASS, ClassificationRun.class.getSimpleName()) .matchAll();//from w ww. j a v a 2 s . co m // Sort by decreasing document order final Sort sort = new Sort(new SortField(null, Type.DOC, true)); final ClassificationRun lastRunToKeep = Iterables .getFirst(search(query, ClassificationRun.class, sort, maximumResultsToKeep - 1, 1), null); if (lastRunToKeep == null) { return; } final Date lastCreationDate = lastRunToKeep.getCreationDate(); final Query trimmingQuery = LongPoint.newRangeQuery(FIELD_CREATION_DATE, Long.MIN_VALUE, lastCreationDate.getTime()); writer.deleteDocuments(trimmingQuery); commit(); }
From source file:com.bewsia.script.safe.lucene.SEntity.java
License:Open Source License
public Sort newSort(SortField... fields) { return new Sort(fields); }
From source file:com.bewsia.script.safe.lucene.SEntity.java
License:Open Source License
public Sort newSort(SortField field) { return new Sort(field); }
From source file:com.codeReading.core.opengrok.SearchHelper.java
License:Open Source License
/** * Create the searcher to use wrt. to currently set parameters and the given * projects. Does not produce any {@link #redirect} link. It also does * nothing if {@link #redirect} or {@link #errorMsg} have a * none-{@code null} value. <p> Parameters which should be populated/set at * this time: <ul> <li>{@link #builder}</li> <li>{@link #dataRoot}</li> * <li>{@link #order} (falls back to relevance if unset)</li> * <li>{@link #parallel} (default: false)</li> </ul> Populates/sets: <ul> * <li>{@link #query}</li> <li>{@link #searcher}</li> <li>{@link #sort}</li> * <li>{@link #projects}</li> <li>{@link #errorMsg} if an error occurs</li> * </ul>/*w w w .ja va 2s .c o m*/ * * @param projects project to use query. If empty, a none-project opengrok * setup is assumed (i.e. DATA_ROOT/index will be used instead of possible * multiple DATA_ROOT/$project/index). * @return this instance */ public SearchHelper prepareExec(SortedSet<String> projects) { if (redirect != null || errorMsg != null) { return this; } // the Query created by the QueryBuilder try { indexDir = new File(dataRoot, "index"); query = builder.build(); if (projects == null) { errorMsg = "No project selected!"; return this; } this.projects = projects; if (projects.isEmpty()) { //no project setup FSDirectory dir = FSDirectory.open(indexDir); searcher = new IndexSearcher(DirectoryReader.open(dir)); } else if (projects.size() == 1) { // just 1 project selected FSDirectory dir = FSDirectory.open(new File(indexDir, projects.first())); searcher = new IndexSearcher(DirectoryReader.open(dir)); } else { //more projects IndexReader[] subreaders = new IndexReader[projects.size()]; int ii = 0; //TODO might need to rewrite to Project instead of // String , need changes in projects.jspf too for (String proj : projects) { FSDirectory dir = FSDirectory.open(new File(indexDir, proj)); subreaders[ii++] = DirectoryReader.open(dir); } MultiReader searchables = new MultiReader(subreaders, true); if (parallel) { int noThreads = 2 + (2 * Runtime.getRuntime().availableProcessors()); //TODO there might be a better way for counting this executor = Executors.newFixedThreadPool(noThreads); } searcher = parallel ? new IndexSearcher(searchables, executor) : new IndexSearcher(searchables); } // TODO check if below is somehow reusing sessions so we don't // requery again and again, I guess 2min timeout sessions could be // usefull, since you click on the next page within 2mins, if not, // then wait ;) switch (order) { case LASTMODIFIED: sort = new Sort(new SortField("date", SortField.Type.STRING, true)); break; case BY_PATH: sort = new Sort(new SortField("fullpath", SortField.Type.STRING)); break; default: sort = Sort.RELEVANCE; break; } checker = new DirectSpellChecker(); } catch (ParseException e) { errorMsg = PARSE_ERROR_MSG + e.getMessage(); } catch (FileNotFoundException e) { // errorMsg = "Index database(s) not found: " + e.getMessage(); errorMsg = "Index database(s) not found."; } catch (Exception e) { errorMsg = e.getMessage(); } return this; }
From source file:com.concursive.connect.indexer.LuceneIndexerSearch.java
License:Open Source License
public void search(IndexerQueryResultList response) { LOG.debug("Search called, using search index type: " + indexType); QueryParser parser = new QueryParser("contents", analyzer); try {/*from w ww . j a v a 2 s . com*/ Hits hits; Query query = parser.parse(response.getQueryString()); if (response.getPagedListInfo().getColumnToSortBy() == null) { hits = searcher.search(query); } else { Sort sort = new Sort(new SortField(response.getPagedListInfo().getColumnToSortBy())); hits = searcher.search(query, sort); } // Convert hits to IndexerResponse objects... convertHits(response, hits); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.dasasian.chok.lucene.integration.LuceneClientTest.java
License:Apache License
@Test public void testFieldSortWithNoResultShard() throws Exception { String indexName = "sortIndex"; File sortIndex = temporaryFolder.newFolder(indexName); File sortShard1 = new File(sortIndex, "sortIndex1"); File sortShard2 = new File(sortIndex, "sortIndex2"); IndexWriter indexWriter1 = new IndexWriter(FSDirectory.open(sortShard1), new StandardAnalyzer(Version.LUCENE_30), true, MaxFieldLength.UNLIMITED); IndexWriter indexWriter2 = new IndexWriter(FSDirectory.open(sortShard2), new StandardAnalyzer(Version.LUCENE_30), true, MaxFieldLength.UNLIMITED); Document document = new Document(); document.add(new Field("text", "abc", Field.Store.YES, Index.NOT_ANALYZED)); document.add(new NumericField("timesort", Field.Store.YES, false).setLongValue(1234567890123l)); indexWriter1.addDocument(document);//from w w w. j av a 2 s . co m indexWriter1.close(); document = new Document(); document.add(new Field("text", "abc2", Field.Store.YES, Index.NOT_ANALYZED)); document.add(new NumericField("timesort", Field.Store.YES, false).setLongValue(1234567890123l)); indexWriter2.addDocument(document); indexWriter2.close(); miniCluster.deployIndex(indexName, sortIndex, 1); // query and compare results LuceneClient client = new LuceneClient(miniCluster.createInteractionProtocol()); Sort sort = new Sort(new SortField[] { new SortField("timesort", SortField.LONG) }); // query both documents Query query = new QueryParser(Version.LUCENE_30, "", new KeywordAnalyzer()).parse("text:ab*"); Hits hits = client.search(query, null, 20, sort); assertEquals(2, hits.size()); // query only one document query = new QueryParser(Version.LUCENE_30, "", new KeywordAnalyzer()).parse("text:abc2"); hits = client.search(query, null, 20, sort); assertEquals(1, hits.size()); // query only one document on one node miniCluster.shutdownNode(0); TestUtil.waitUntilIndexBalanced(miniCluster.getProtocol(), indexName); query = new QueryParser(Version.LUCENE_30, "", new KeywordAnalyzer()).parse("text:abc2"); hits = client.search(query, null, 20, sort); assertEquals(1, hits.size()); client.close(); }
From source file:com.dasasian.chok.lucene.integration.LuceneClientTest.java
License:Apache License
@SuppressWarnings("unchecked") @Test/*w w w.j a v a2 s .c o m*/ public void testSortedSearch() throws Exception { // write and deploy test index String queryTerm = "2"; String textFieldName = "textField"; File sortIndex = temporaryFolder.newFolder("sortIndex2"); File sortShard = new File(sortIndex, "sortShard"); String sortFieldName = "sortField"; IndexWriter indexWriter = new IndexWriter(FSDirectory.open(sortShard), new StandardAnalyzer(Version.LUCENE_30), true, MaxFieldLength.UNLIMITED); for (int i = 0; i < 20; i++) { Document document = new Document(); document.add(new Field(sortFieldName, "" + i, Store.NO, Index.NOT_ANALYZED)); String textField = "sample text"; if (i % 2 == 0) {// produce some different scores for (int j = 0; j < i; j++) { textField += " " + queryTerm; } } document.add(new Field(textFieldName, textField, Store.NO, Index.ANALYZED)); indexWriter.addDocument(document); } indexWriter.close(true); DeployClient deployClient = new DeployClient(miniCluster.getProtocol()); IndexState indexState = deployClient.addIndex(sortIndex.getName(), sortIndex.getAbsolutePath(), 1) .joinDeployment(); assertEquals(IndexState.DEPLOYED, indexState); // query and compare results LuceneClient client = new LuceneClient(miniCluster.createInteractionProtocol()); final Query query = new QueryParser(Version.LUCENE_30, "", new KeywordAnalyzer()) .parse(textFieldName + ": " + queryTerm); Sort sort = new Sort(new SortField[] { new SortField(sortFieldName, SortField.INT) }); final Hits hits = client.search(query, new String[] { sortIndex.getName() }, 20, sort); assertNotNull(hits); List<Hit> hitsList = hits.getHits(); for (final Hit hit : hitsList) { writeToLog(hit); } assertEquals(9, hits.size()); assertEquals(9, hitsList.size()); assertEquals(1, hitsList.get(0).getSortFields().length); for (int i = 0; i < hitsList.size() - 1; i++) { int compareTo = hitsList.get(i).getSortFields()[0].compareTo(hitsList.get(i + 1).getSortFields()[0]); assertTrue("results not after field", compareTo == 0 || compareTo == -1); } client.close(); }
From source file:com.dasasian.chok.lucene.integration.LuceneComplianceTest.java
License:Apache License
@Test public void testFieldSort() throws Exception { // query and compare (auto types) IndexSearcher indexSearcher = new IndexSearcher(FSDirectory.open(luceneIndex.getAbsoluteFile())); Sort sort = new Sort(new SortField[] { new SortField(FIELD_NAME, SortField.LONG) }); checkQueryResults(indexSearcher, chokIndex.getName(), FIELD_NAME, "0", sort); checkQueryResults(indexSearcher, chokIndex.getName(), FIELD_NAME, "1", sort); checkQueryResults(indexSearcher, chokIndex.getName(), FIELD_NAME, "2", sort); checkQueryResults(indexSearcher, chokIndex.getName(), FIELD_NAME, "15", sort); checkQueryResults(indexSearcher, chokIndex.getName(), FIELD_NAME, "23", sort); checkQueryResults(indexSearcher, chokIndex.getName(), FIELD_NAME, "2 23", sort); checkQueryResults(indexSearcher, chokIndex.getName(), FIELD_NAME, "nothing", sort); // check for explicit types sort = new Sort(new SortField[] { new SortField(FIELD_NAME, SortField.BYTE) }); checkQueryResults(indexSearcher, chokIndex.getName(), FIELD_NAME, "1", sort); sort = new Sort(new SortField[] { new SortField(FIELD_NAME, SortField.INT) }); checkQueryResults(indexSearcher, chokIndex.getName(), FIELD_NAME, "1", sort); sort = new Sort(new SortField[] { new SortField(FIELD_NAME, SortField.LONG) }); checkQueryResults(indexSearcher, chokIndex.getName(), FIELD_NAME, "1", sort); }
From source file:com.dp2345.service.impl.SearchServiceImpl.java
License:Open Source License
@SuppressWarnings("unchecked") @Transactional(readOnly = true)/* ww w . j a v a 2s . com*/ public Page<Article> search(String keyword, Pageable pageable) { if (StringUtils.isEmpty(keyword)) { return new Page<Article>(); } if (pageable == null) { pageable = new Pageable(); } try { String text = QueryParser.escape(keyword); QueryParser titleParser = new QueryParser(Version.LUCENE_35, "title", new IKAnalyzer()); titleParser.setDefaultOperator(QueryParser.AND_OPERATOR); Query titleQuery = titleParser.parse(text); FuzzyQuery titleFuzzyQuery = new FuzzyQuery(new Term("title", text), FUZZY_QUERY_MINIMUM_SIMILARITY); Query contentQuery = new TermQuery(new Term("content", text)); Query isPublicationQuery = new TermQuery(new Term("isPublication", "true")); BooleanQuery textQuery = new BooleanQuery(); BooleanQuery query = new BooleanQuery(); textQuery.add(titleQuery, Occur.SHOULD); textQuery.add(titleFuzzyQuery, Occur.SHOULD); textQuery.add(contentQuery, Occur.SHOULD); query.add(isPublicationQuery, Occur.MUST); query.add(textQuery, Occur.MUST); FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager); FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery(query, Article.class); fullTextQuery.setSort(new Sort(new SortField[] { new SortField("isTop", SortField.STRING, true), new SortField(null, SortField.SCORE), new SortField("createDate", SortField.LONG, true) })); fullTextQuery.setFirstResult((pageable.getPageNumber() - 1) * pageable.getPageSize()); fullTextQuery.setMaxResults(pageable.getPageSize()); return new Page<Article>(fullTextQuery.getResultList(), fullTextQuery.getResultSize(), pageable); } catch (ParseException e) { e.printStackTrace(); } return new Page<Article>(); }
From source file:com.dp2345.service.impl.SearchServiceImpl.java
License:Open Source License
@SuppressWarnings("unchecked") @Transactional(readOnly = true)/*from ww w. j a v a 2s . c o m*/ public Page<Product> search(String keyword, BigDecimal startPrice, BigDecimal endPrice, OrderType orderType, Pageable pageable) { if (StringUtils.isEmpty(keyword)) { return new Page<Product>(); } if (pageable == null) { pageable = new Pageable(); } try { String text = QueryParser.escape(keyword); TermQuery snQuery = new TermQuery(new Term("sn", text)); Query keywordQuery = new QueryParser(Version.LUCENE_35, "keyword", new IKAnalyzer()).parse(text); QueryParser nameParser = new QueryParser(Version.LUCENE_35, "name", new IKAnalyzer()); nameParser.setDefaultOperator(QueryParser.AND_OPERATOR); Query nameQuery = nameParser.parse(text); FuzzyQuery nameFuzzyQuery = new FuzzyQuery(new Term("name", text), FUZZY_QUERY_MINIMUM_SIMILARITY); TermQuery introductionQuery = new TermQuery(new Term("introduction", text)); TermQuery isMarketableQuery = new TermQuery(new Term("isMarketable", "true")); TermQuery isListQuery = new TermQuery(new Term("isList", "true")); TermQuery isGiftQuery = new TermQuery(new Term("isGift", "false")); BooleanQuery textQuery = new BooleanQuery(); BooleanQuery query = new BooleanQuery(); textQuery.add(snQuery, Occur.SHOULD); textQuery.add(keywordQuery, Occur.SHOULD); textQuery.add(nameQuery, Occur.SHOULD); textQuery.add(nameFuzzyQuery, Occur.SHOULD); textQuery.add(introductionQuery, Occur.SHOULD); query.add(isMarketableQuery, Occur.MUST); query.add(isListQuery, Occur.MUST); query.add(isGiftQuery, Occur.MUST); query.add(textQuery, Occur.MUST); if (startPrice != null && endPrice != null && startPrice.compareTo(endPrice) > 0) { BigDecimal temp = startPrice; startPrice = endPrice; endPrice = temp; } if (startPrice != null && startPrice.compareTo(new BigDecimal(0)) >= 0 && endPrice != null && endPrice.compareTo(new BigDecimal(0)) >= 0) { NumericRangeQuery<Double> numericRangeQuery = NumericRangeQuery.newDoubleRange("price", startPrice.doubleValue(), endPrice.doubleValue(), true, true); query.add(numericRangeQuery, Occur.MUST); } else if (startPrice != null && startPrice.compareTo(new BigDecimal(0)) >= 0) { NumericRangeQuery<Double> numericRangeQuery = NumericRangeQuery.newDoubleRange("price", startPrice.doubleValue(), null, true, false); query.add(numericRangeQuery, Occur.MUST); } else if (endPrice != null && endPrice.compareTo(new BigDecimal(0)) >= 0) { NumericRangeQuery<Double> numericRangeQuery = NumericRangeQuery.newDoubleRange("price", null, endPrice.doubleValue(), false, true); query.add(numericRangeQuery, Occur.MUST); } FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager); FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery(query, Product.class); SortField[] sortFields = null; if (orderType == OrderType.priceAsc) { sortFields = new SortField[] { new SortField("price", SortField.DOUBLE, false), new SortField("createDate", SortField.LONG, true) }; } else if (orderType == OrderType.priceDesc) { sortFields = new SortField[] { new SortField("price", SortField.DOUBLE, true), new SortField("createDate", SortField.LONG, true) }; } else if (orderType == OrderType.salesDesc) { sortFields = new SortField[] { new SortField("sales", SortField.INT, true), new SortField("createDate", SortField.LONG, true) }; } else if (orderType == OrderType.scoreDesc) { sortFields = new SortField[] { new SortField("score", SortField.INT, true), new SortField("createDate", SortField.LONG, true) }; } else if (orderType == OrderType.dateDesc) { sortFields = new SortField[] { new SortField("createDate", SortField.LONG, true) }; } else { sortFields = new SortField[] { new SortField("isTop", SortField.STRING, true), new SortField(null, SortField.SCORE), new SortField("modifyDate", SortField.LONG, true) }; } fullTextQuery.setSort(new Sort(sortFields)); fullTextQuery.setFirstResult((pageable.getPageNumber() - 1) * pageable.getPageSize()); fullTextQuery.setMaxResults(pageable.getPageSize()); return new Page<Product>(fullTextQuery.getResultList(), fullTextQuery.getResultSize(), pageable); } catch (Exception e) { e.printStackTrace(); } return new Page<Product>(); }