List of usage examples for org.apache.lucene.search Sort Sort
public Sort(SortField... fields)
From source file:luceneexamples.NumericFieldDocument.java
License:Apache License
@Test public void index() throws Exception { RAMDirectory directory = new RAMDirectory(); Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_31); IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_31, analyzer); IndexWriter writer = new IndexWriter(directory, iwc); for (int i = 8; i < 12; i++) { Document doc = new Document(); doc.add(new NumericField("int_field", Field.Store.YES, true).setIntValue(i)); System.out.println(doc);/* w w w . j ava2 s. c om*/ writer.addDocument(doc); } writer.commit(); IndexReader reader = IndexReader.open(writer, true); IndexSearcher searcher = new IndexSearcher(reader); TopDocs td = searcher.search(new MatchAllDocsQuery(), 1000, new Sort(new SortField("int_field", SortField.INT))); assertThat(td.totalHits, is(4)); assertThat(searcher.doc(td.scoreDocs[0].doc).get("int_field"), equalTo("8")); assertThat(searcher.doc(td.scoreDocs[1].doc).get("int_field"), equalTo("9")); assertThat(searcher.doc(td.scoreDocs[2].doc).get("int_field"), equalTo("10")); assertThat(searcher.doc(td.scoreDocs[3].doc).get("int_field"), equalTo("11")); reader.close(); writer.close(); searcher.close(); directory.close(); }
From source file:luceneexamples.SortDocuments.java
License:Apache License
@Test public void index() throws Exception { RAMDirectory directory = new RAMDirectory(); Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_31); IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_31, analyzer); IndexWriter writer = new IndexWriter(directory, iwc); Document doc = new Document(); doc.add(new Field("str_field", "abc", Field.Store.YES, Field.Index.ANALYZED)); writer.addDocument(doc);/*from ww w .jav a 2s . c o m*/ Document doc2 = new Document(); doc2.add(new Field("str_field", "def", Field.Store.YES, Field.Index.ANALYZED)); writer.addDocument(doc2); Document doc3 = new Document(); doc3.add(new Field("str_field", "hij", Field.Store.YES, Field.Index.ANALYZED)); writer.addDocument(doc3); writer.commit(); IndexReader reader = IndexReader.open(writer, true); IndexSearcher searcher = new IndexSearcher(reader); TopDocs td = searcher.search(new MatchAllDocsQuery(), 1000, new Sort(new SortField("str_field", SortField.STRING))); assertThat(td.totalHits, is(3)); assertThat(searcher.doc(td.scoreDocs[0].doc).get("str_field"), equalTo("abc")); assertThat(searcher.doc(td.scoreDocs[1].doc).get("str_field"), equalTo("def")); assertThat(searcher.doc(td.scoreDocs[2].doc).get("str_field"), equalTo("hij")); td = searcher.search(new MatchAllDocsQuery(), 1000, new Sort(new SortField("str_field", SortField.STRING, true))); assertThat(td.totalHits, is(3)); assertThat(searcher.doc(td.scoreDocs[0].doc).get("str_field"), equalTo("hij")); assertThat(searcher.doc(td.scoreDocs[1].doc).get("str_field"), equalTo("def")); assertThat(searcher.doc(td.scoreDocs[2].doc).get("str_field"), equalTo("abc")); reader.close(); writer.close(); searcher.close(); directory.close(); }
From source file:net.jforum.core.hibernate.SearchDAO.java
License:Open Source License
@SuppressWarnings("unchecked") public SearchResult search(SearchParams params) throws ParseException { String buildQuery = params.buildQuery(); FullTextQuery query = this.createQuery(buildQuery); query.setFirstResult(params.getStart()); query.setMaxResults(params.getMaxResults()); query.setFetchSize(params.getMaxResults()); if (params.getSort() == SearchSort.DATE) { query.setSort(new Sort(new SortField("date", params.getSortType() == SearchSortType.DESC))); } else if (params.getSort() == SearchSort.RELEVANCE) { query.setSort(Sort.RELEVANCE);//ww w . j ava 2 s. c om } return new SearchResult(query.list(), query.getResultSize()); }
From source file:net.mojodna.searchable.AbstractSearcher.java
License:Apache License
/** * Search the index with the specified query. * /*from w ww. j a v a2 s. c om*/ * @param query Query to use. * @param filter Filter to use. * @param offset Offset to begin result set at. * @param count Number of results to return. * @param sortField Field to sort by. * @return ResultSet containing results. * @throws IndexException */ // TODO add support for String[] sortFields protected ResultSet doSearch(final Query query, final Filter filter, final Integer offset, final Integer count, final String sortField) throws IndexException { Sort sort = Sort.RELEVANCE; if (StringUtils.isNotBlank(sortField)) sort = new Sort(IndexSupport.SORTABLE_PREFIX + sortField); return doSearch(query, filter, offset, count, sort); }
From source file:net.mojodna.searchable.AbstractSearcher.java
License:Apache License
/** * Search the index with the specified query. * /*from w ww. j av a2 s . c o m*/ * @param query Query to use. * @param offset Offset to begin result set at. * @param count Number of results to return. * @param sortField Field to sort by. * @return ResultSet containing results. * @throws IndexException */ // TODO add support for String[] sortFields protected ResultSet doSearch(final Query query, final Integer offset, final Integer count, final String sortField) throws IndexException { Sort sort = Sort.RELEVANCE; if (StringUtils.isNotBlank(sortField)) sort = new Sort(IndexSupport.SORTABLE_PREFIX + sortField); return doSearch(query, offset, count, sort); }
From source file:net.sf.katta.integrationTest.lib.lucene.LuceneClientTest.java
License:Apache License
@Test public void testFieldSortWithNoResultShard() throws Exception { File sortIndex1 = _temporaryFolder.newFolder("sortIndex1"); File sortIndex2 = _temporaryFolder.newFolder("sortIndex2"); IndexWriter indexWriter1 = new IndexWriter(FSDirectory.open(sortIndex1), new StandardAnalyzer(Version.LUCENE_35), true, MaxFieldLength.UNLIMITED); IndexWriter indexWriter2 = new IndexWriter(FSDirectory.open(sortIndex2), new StandardAnalyzer(Version.LUCENE_35), 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 ww .j a v a2 s . c o 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(); DeployClient deployClient = new DeployClient(_miniCluster.getProtocol()); String indexName = "sortIndex"; IndexState indexState = deployClient.addIndex(indexName, sortIndex1.getParentFile().getAbsolutePath(), 1) .joinDeployment(); assertEquals(IndexState.DEPLOYED, indexState); // query and compare results ILuceneClient client = new LuceneClient(_miniCluster.getZkConfiguration()); Sort sort = new Sort(new SortField[] { new SortField("timesort", SortField.LONG) }); // query both documents Query query = new QueryParser(Version.LUCENE_35, "", new KeywordAnalyzer()).parse("text:ab*"); Hits hits = client.search(query, new String[] { indexName }, 20, sort); assertEquals(2, hits.size()); // query only one document query = new QueryParser(Version.LUCENE_35, "", new KeywordAnalyzer()).parse("text:abc2"); hits = client.search(query, new String[] { indexName }, 20, sort); assertEquals(1, hits.size()); // query only one document on one node _miniCluster.shutdownNode(0); TestUtil.waitUntilIndexBalanced(_protocol, indexName); query = new QueryParser(Version.LUCENE_35, "", new KeywordAnalyzer()).parse("text:abc2"); hits = client.search(query, new String[] { indexName }, 20, sort); assertEquals(1, hits.size()); client.close(); }
From source file:net.sf.katta.integrationTest.lib.lucene.LuceneClientTest.java
License:Apache License
@SuppressWarnings("unchecked") @Test//w ww.ja va 2 s . c o m public void testSortedSearch() throws Exception { // write and deploy test index File sortIndex = _temporaryFolder.newFolder("sortIndex2"); String queryTerm = "2"; String sortFieldName = "sortField"; String textFieldName = "textField"; IndexWriter indexWriter = new IndexWriter(FSDirectory.open(sortIndex), new StandardAnalyzer(Version.LUCENE_35), 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.optimize(); indexWriter.close(); DeployClient deployClient = new DeployClient(_miniCluster.getProtocol()); IndexState indexState = deployClient .addIndex(sortIndex.getName(), sortIndex.getParentFile().getAbsolutePath(), 1).joinDeployment(); assertEquals(IndexState.DEPLOYED, indexState); // query and compare results ILuceneClient client = new LuceneClient(_miniCluster.getZkConfiguration()); final Query query = new QueryParser(Version.LUCENE_35, "", new KeywordAnalyzer()) .parse(textFieldName + ": " + queryTerm); Sort sort = new Sort(new SortField[] { new SortField("sortField", 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", 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:net.sf.katta.integrationTest.lib.lucene.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, _kattaIndex.getName(), FIELD_NAME, "0", sort); checkQueryResults(indexSearcher, _kattaIndex.getName(), FIELD_NAME, "1", sort); checkQueryResults(indexSearcher, _kattaIndex.getName(), FIELD_NAME, "2", sort); checkQueryResults(indexSearcher, _kattaIndex.getName(), FIELD_NAME, "15", sort); checkQueryResults(indexSearcher, _kattaIndex.getName(), FIELD_NAME, "23", sort); checkQueryResults(indexSearcher, _kattaIndex.getName(), FIELD_NAME, "2 23", sort); checkQueryResults(indexSearcher, _kattaIndex.getName(), FIELD_NAME, "nothing", sort); // check for explicit types sort = new Sort(new SortField[] { new SortField(FIELD_NAME, SortField.BYTE) }); checkQueryResults(indexSearcher, _kattaIndex.getName(), FIELD_NAME, "1", sort); sort = new Sort(new SortField[] { new SortField(FIELD_NAME, SortField.INT) }); checkQueryResults(indexSearcher, _kattaIndex.getName(), FIELD_NAME, "1", sort); sort = new Sort(new SortField[] { new SortField(FIELD_NAME, SortField.LONG) }); checkQueryResults(indexSearcher, _kattaIndex.getName(), FIELD_NAME, "1", sort); }
From source file:net.sf.logsaw.index.internal.LuceneIndexServiceImpl.java
License:Open Source License
@Override public ResultPage query(IQueryContext context, final List<ARestriction<?>> restrictions, final int offset, final int limit) throws CoreException { Assert.isNotNull(context, "context"); //$NON-NLS-1$ Assert.isTrue(context instanceof LuceneQueryContextImpl, "Query context must be of type net.sf.logsaw.index.impl.LuceneQueryContextImpl"); //$NON-NLS-1$ Assert.isTrue(context.isOpen(), "Query context must be open"); //$NON-NLS-1$ Assert.isNotNull(restrictions, "restrictions"); //$NON-NLS-1$ ARunWithIndexReader<ResultPage> runnable = new ARunWithIndexReader<ResultPage>() { /* (non-Javadoc) * @see net.sf.logsaw.index.impl.ARunWithIndexReader#doRunWithIndexReader(org.apache.lucene.index.IndexReader, net.sf.logsaw.core.framework.ILogResource) *//* w w w. jav a2 s.c o m*/ @Override protected ResultPage doRunWithIndexReader(IndexReader reader, ILogResource log) throws CoreException { if (reader == null) { // Index does not exist yet return new ResultPage(); } try { IndexSearcher searcher = new IndexSearcher(reader); Sort sort = new Sort(new SortField[] { SortField.FIELD_DOC }); TopFieldCollector collector = TopFieldCollector.create(sort, offset + limit, false, false, false, true); // TODO Investigate use of searchAfter searcher.search(convertToQuery(restrictions), collector); List<LogEntry> result = new LinkedList<LogEntry>(); collectHits(searcher, collector.topDocs(offset), log.getDialect(), result); return new ResultPage(result, offset, collector.getTotalHits()); } catch (IOException e) { // Unexpected exception; wrap with CoreException throw new CoreException(new Status(IStatus.ERROR, IndexPlugin.PLUGIN_ID, NLS.bind(Messages.LuceneIndexService_error_failedToReadIndex, new Object[] { log.getName(), e.getLocalizedMessage() }), e)); } } }; runnable.setQueryContext((LuceneQueryContextImpl) context); return runnable.runWithIndexReader(context.getLogResource()); }
From source file:net.tourbook.search.FTSearchManager.java
License:Open Source License
/** * @param searchText/*from w ww.j av a 2 s . com*/ * @param searchFrom * @param searchTo * @param searchResult * @return */ private static void search(final String searchText, final int searchFrom, final int searchTo, final SearchResult searchResult) { try { setupIndexReader(); final int maxDoc = _indexReader.maxDoc(); if (maxDoc == 0) { // there are 0 documents searchResult.totalHits = 0; return; } final String[] queryFields = { // SEARCH_FIELD_TITLE, SEARCH_FIELD_DESCRIPTION, // }; final int maxPassages[] = new int[queryFields.length]; Arrays.fill(maxPassages, 1); final Analyzer analyzer = getAnalyzer(); final MultiFieldQueryParser queryParser = new MultiFieldQueryParser(queryFields, analyzer); queryParser.setAllowLeadingWildcard(true); final Query query = queryParser.parse(searchText); if (_topDocsSearchText == null || _topDocsSearchText.equals(searchText) == false || true) { // this is a new search /* * Set sorting */ final SortField sortByTime = new SortField(SEARCH_FIELD_TIME, Type.LONG, _isSortDateAscending == false); final Sort sort = new Sort(sortByTime); if (_isShowContentAll) { // no filtering _topDocs = _indexSearcher.search(query, maxDoc, sort); } else { // filter by content final BooleanFilter searchFilter = new BooleanFilter(); if (_isShowContentMarker) { final NumericRangeFilter<Integer> filter = NumericRangeFilter.newIntRange( SEARCH_FIELD_DOC_SOURCE, DOC_SOURCE_TOUR_MARKER, DOC_SOURCE_TOUR_MARKER, true, true); searchFilter.add(new FilterClause(filter, Occur.SHOULD)); } if (_isShowContentTour) { final NumericRangeFilter<Integer> filter = NumericRangeFilter .newIntRange(SEARCH_FIELD_DOC_SOURCE, DOC_SOURCE_TOUR, DOC_SOURCE_TOUR, true, true); searchFilter.add(new FilterClause(filter, Occur.SHOULD)); } if (_isShowContentWaypoint) { final NumericRangeFilter<Integer> filter = NumericRangeFilter.newIntRange( SEARCH_FIELD_DOC_SOURCE, DOC_SOURCE_WAY_POINT, DOC_SOURCE_WAY_POINT, true, true); searchFilter.add(new FilterClause(filter, Occur.SHOULD)); } _topDocs = _indexSearcher.search(query, searchFilter, maxDoc, sort); } _topDocsSearchText = searchText; } searchResult.totalHits = _topDocs.totalHits; /** * Get doc id's only for the current page. * <p> * It is very cheap to query the doc id's but very expensive to retrieve the documents. */ final int docStartIndex = searchFrom; int docEndIndex = searchTo; final ScoreDoc[] scoreDocs = _topDocs.scoreDocs; final int scoreSize = scoreDocs.length; if (docEndIndex >= scoreSize) { docEndIndex = scoreSize - 1; } final int resultSize = docEndIndex - docStartIndex + 1; final int docids[] = new int[resultSize]; for (int docIndex = 0; docIndex < resultSize; docIndex++) { docids[docIndex] = scoreDocs[docStartIndex + docIndex].doc; } // this can occure: field 'description' was indexed without offsets, cannot highlight final MyPostingsHighlighter highlighter = new MyPostingsHighlighter(); final Map<String, String[]> highlights = highlighter.highlightFields(queryFields, query, _indexSearcher, docids, maxPassages); search_CreateResult(highlights, _indexReader, searchResult, docids, docStartIndex); } catch (final Exception e) { StatusUtil.showStatus(e); searchResult.error = e.getMessage(); } }