当前位置: 首页>>代码示例>>Java>>正文


Java IndexSearcher类代码示例

本文整理汇总了Java中org.apache.lucene.search.IndexSearcher的典型用法代码示例。如果您正苦于以下问题:Java IndexSearcher类的具体用法?Java IndexSearcher怎么用?Java IndexSearcher使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


IndexSearcher类属于org.apache.lucene.search包,在下文中一共展示了IndexSearcher类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: testSimpleNumericOps

import org.apache.lucene.search.IndexSearcher; //导入依赖的package包/类
public void testSimpleNumericOps() throws Exception {
    Directory dir = new RAMDirectory();
    IndexWriter indexWriter = new IndexWriter(dir, new IndexWriterConfig(Lucene.STANDARD_ANALYZER));

    Document document = new Document();
    document.add(new TextField("_id", "1", Field.Store.YES));
    document.add(new LegacyIntField("test", 2, LegacyIntField.TYPE_STORED));
    indexWriter.addDocument(document);

    IndexReader reader = DirectoryReader.open(indexWriter);
    IndexSearcher searcher = new IndexSearcher(reader);
    TopDocs topDocs = searcher.search(new TermQuery(new Term("_id", "1")), 1);
    Document doc = searcher.doc(topDocs.scoreDocs[0].doc);
    IndexableField f = doc.getField("test");
    assertThat(f.stringValue(), equalTo("2"));

    BytesRefBuilder bytes = new BytesRefBuilder();
    LegacyNumericUtils.intToPrefixCoded(2, 0, bytes);
    topDocs = searcher.search(new TermQuery(new Term("test", bytes.get())), 1);
    doc = searcher.doc(topDocs.scoreDocs[0].doc);
    f = doc.getField("test");
    assertThat(f.stringValue(), equalTo("2"));

    indexWriter.close();
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:26,代码来源:SimpleLuceneTests.java

示例2: testMMapDirectory

import org.apache.lucene.search.IndexSearcher; //导入依赖的package包/类
public void testMMapDirectory() throws IOException {
    long start = System.currentTimeMillis();
    IndexWriterConfig indexWriterConfig = new IndexWriterConfig(new WhitespaceAnalyzer()).setOpenMode(IndexWriterConfig
            .OpenMode.CREATE);
    FSDirectory open = FSDirectory.open(Paths.get("E:/testlucene"));
    IndexWriter indexWriter = new IndexWriter(open, indexWriterConfig);
    for (int i = 0; i < 10000000; i++) {
        indexWriter.addDocument(addDocument(i));
    }
    indexWriter.commit();
    indexWriter.close();
    long end = System.currentTimeMillis();
    log.error("MMapDirectory consumes {}s!", (end - start) / 1000);
    start = System.currentTimeMillis();
    IndexSearcher indexSearcher = new IndexSearcher(DirectoryReader.open(open));
    int total = 0;
    for (int i = 0; i < 10000000; i++) {
        TermQuery key1 = new TermQuery(new Term("key1", "key" + i));
        TopDocs search = indexSearcher.search(key1, 10);
        total += search.totalHits;
    }
    System.out.println(total);
    end = System.currentTimeMillis();
    log.error("MMapDirectory search consumes {}ms!", (end - start));
}
 
开发者ID:shijiebei2009,项目名称:RedisDirectory,代码行数:26,代码来源:TestLucene.java

示例3: duelRun

import org.apache.lucene.search.IndexSearcher; //导入依赖的package包/类
private void duelRun(PercolateQuery.QueryStore queryStore, MemoryIndex memoryIndex, IndexSearcher shardSearcher) throws IOException {
    boolean requireScore = randomBoolean();
    IndexSearcher percolateSearcher = memoryIndex.createSearcher();
    Query percolateQuery = fieldType.percolateQuery("type", queryStore, new BytesArray("{}"), percolateSearcher);
    Query query = requireScore ? percolateQuery : new ConstantScoreQuery(percolateQuery);
    TopDocs topDocs = shardSearcher.search(query, 10);

    Query controlQuery = new ControlQuery(memoryIndex, queryStore);
    controlQuery = requireScore ? controlQuery : new ConstantScoreQuery(controlQuery);
    TopDocs controlTopDocs = shardSearcher.search(controlQuery, 10);
    assertThat(topDocs.totalHits, equalTo(controlTopDocs.totalHits));
    assertThat(topDocs.scoreDocs.length, equalTo(controlTopDocs.scoreDocs.length));
    for (int j = 0; j < topDocs.scoreDocs.length; j++) {
        assertThat(topDocs.scoreDocs[j].doc, equalTo(controlTopDocs.scoreDocs[j].doc));
        assertThat(topDocs.scoreDocs[j].score, equalTo(controlTopDocs.scoreDocs[j].score));
        if (requireScore) {
            Explanation explain1 = shardSearcher.explain(query, topDocs.scoreDocs[j].doc);
            Explanation explain2 = shardSearcher.explain(controlQuery, controlTopDocs.scoreDocs[j].doc);
            assertThat(explain1.isMatch(), equalTo(explain2.isMatch()));
            assertThat(explain1.getValue(), equalTo(explain2.getValue()));
        }
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:24,代码来源:CandidateQueryTests.java

示例4: assertAvgScoreMode

import org.apache.lucene.search.IndexSearcher; //导入依赖的package包/类
protected void assertAvgScoreMode(Query parentFilter, IndexSearcher searcher, IndexFieldData.XFieldComparatorSource innerFieldComparator) throws IOException {
    MultiValueMode sortMode = MultiValueMode.AVG;
    Query childFilter = Queries.not(parentFilter);
    XFieldComparatorSource nestedComparatorSource = createFieldComparator("field2", sortMode, -127, createNested(searcher, parentFilter, childFilter));
    Query query = new ToParentBlockJoinQuery(new ConstantScoreQuery(childFilter), new QueryBitSetProducer(parentFilter), ScoreMode.None);
    Sort sort = new Sort(new SortField("field2", nestedComparatorSource));
    TopDocs topDocs = searcher.search(query, 5, sort);
    assertThat(topDocs.totalHits, equalTo(7));
    assertThat(topDocs.scoreDocs.length, equalTo(5));
    assertThat(topDocs.scoreDocs[0].doc, equalTo(11));
    assertThat(((Number) ((FieldDoc) topDocs.scoreDocs[0]).fields[0]).intValue(), equalTo(2));
    assertThat(topDocs.scoreDocs[1].doc, equalTo(7));
    assertThat(((Number) ((FieldDoc) topDocs.scoreDocs[1]).fields[0]).intValue(), equalTo(2));
    assertThat(topDocs.scoreDocs[2].doc, equalTo(3));
    assertThat(((Number) ((FieldDoc) topDocs.scoreDocs[2]).fields[0]).intValue(), equalTo(3));
    assertThat(topDocs.scoreDocs[3].doc, equalTo(15));
    assertThat(((Number) ((FieldDoc) topDocs.scoreDocs[3]).fields[0]).intValue(), equalTo(3));
    assertThat(topDocs.scoreDocs[4].doc, equalTo(19));
    assertThat(((Number) ((FieldDoc) topDocs.scoreDocs[4]).fields[0]).intValue(), equalTo(3));
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:21,代码来源:FloatNestedSortingTests.java

示例5: assertAvgScoreMode

import org.apache.lucene.search.IndexSearcher; //导入依赖的package包/类
@Override
protected void assertAvgScoreMode(Query parentFilter, IndexSearcher searcher) throws IOException {
    MultiValueMode sortMode = MultiValueMode.AVG;
    Query childFilter = Queries.not(parentFilter);
    XFieldComparatorSource nestedComparatorSource = createFieldComparator("field2", sortMode, -127, createNested(searcher, parentFilter, childFilter));
    Query query = new ToParentBlockJoinQuery(new ConstantScoreQuery(childFilter), new QueryBitSetProducer(parentFilter), ScoreMode.None);
    Sort sort = new Sort(new SortField("field2", nestedComparatorSource));
    TopDocs topDocs = searcher.search(query, 5, sort);
    assertThat(topDocs.totalHits, equalTo(7));
    assertThat(topDocs.scoreDocs.length, equalTo(5));
    assertThat(topDocs.scoreDocs[0].doc, equalTo(11));
    assertThat(((Number) ((FieldDoc) topDocs.scoreDocs[0]).fields[0]).intValue(), equalTo(2));
    assertThat(topDocs.scoreDocs[1].doc, equalTo(7));
    assertThat(((Number) ((FieldDoc) topDocs.scoreDocs[1]).fields[0]).intValue(), equalTo(2));
    assertThat(topDocs.scoreDocs[2].doc, equalTo(3));
    assertThat(((Number) ((FieldDoc) topDocs.scoreDocs[2]).fields[0]).intValue(), equalTo(3));
    assertThat(topDocs.scoreDocs[3].doc, equalTo(15));
    assertThat(((Number) ((FieldDoc) topDocs.scoreDocs[3]).fields[0]).intValue(), equalTo(3));
    assertThat(topDocs.scoreDocs[4].doc, equalTo(19));
    assertThat(((Number) ((FieldDoc) topDocs.scoreDocs[4]).fields[0]).intValue(), equalTo(3));
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:22,代码来源:DoubleNestedSortingTests.java

示例6: testVectorHighlighterNoStore

import org.apache.lucene.search.IndexSearcher; //导入依赖的package包/类
public void testVectorHighlighterNoStore() throws Exception {
    Directory dir = new RAMDirectory();
    IndexWriter indexWriter = new IndexWriter(dir, new IndexWriterConfig(Lucene.STANDARD_ANALYZER));

    Document document = new Document();
    document.add(new TextField("_id", "1", Field.Store.YES));
    FieldType vectorsType = new FieldType(TextField.TYPE_NOT_STORED);
    vectorsType.setStoreTermVectors(true);
    vectorsType.setStoreTermVectorPositions(true);
    vectorsType.setStoreTermVectorOffsets(true);
    document.add(new Field("content", "the big bad dog", vectorsType));
    indexWriter.addDocument(document);

    IndexReader reader = DirectoryReader.open(indexWriter);
    IndexSearcher searcher = new IndexSearcher(reader);
    TopDocs topDocs = searcher.search(new TermQuery(new Term("_id", "1")), 1);

    assertThat(topDocs.totalHits, equalTo(1));

    FastVectorHighlighter highlighter = new FastVectorHighlighter();
    String fragment = highlighter.getBestFragment(highlighter.getFieldQuery(new TermQuery(new Term("content", "bad"))),
            reader, topDocs.scoreDocs[0].doc, "content", 30);
    assertThat(fragment, nullValue());
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:25,代码来源:VectorHighlighterTests.java

示例7: findByAuthorSurname

import org.apache.lucene.search.IndexSearcher; //导入依赖的package包/类
/**
 * Search all books of a given author. 
 * 
 * @throws Exception never, otherwise the test fails.
 */
@Test
public void findByAuthorSurname() throws Exception {
	IndexSearcher searcher = new IndexSearcher(DirectoryReader.open(directory));
	
	Query query = new QueryParser("author", new StandardAnalyzer()).parse("Gazzarini");
	TopDocs matches = searcher.search(query, 10);
	
	assertEquals(1, matches.totalHits);
			
	final String id = Arrays.stream(matches.scoreDocs)
		.map(scoreDoc -> luceneDoc(scoreDoc.doc, searcher))
		.map(doc -> doc.get("id"))
		.findFirst()
		.get();
	
	assertEquals("1", id);
}
 
开发者ID:agazzarini,项目名称:as-full-text-search-server,代码行数:23,代码来源:LuceneBasicFlowExampleTestCase.java

示例8: checkIndexContent

import org.apache.lucene.search.IndexSearcher; //导入依赖的package包/类
private void checkIndexContent(final String elementId,
		final String fieldContent, final int expectedAmount) throws IOException {
	final IndexReader reader = IndexManager.getInstance().getIndex().getIndexReader();
	final IndexSearcher searcher = new IndexSearcher(reader);
	final TopDocs topDocs = searcher.search(new TermQuery(new Term(FIELDNAME, fieldContent)), expectedAmount + 10);

	assertNotNull(topDocs);
	assertTrue(topDocs.totalHits == expectedAmount);

	if(expectedAmount > 0) {
		final ScoreDoc scoreDoc = topDocs.scoreDocs[0];
		assertNotNull(scoreDoc);

		final Document doc = reader.document(scoreDoc.doc);
		assertNotNull(doc);
		assertEquals(fieldContent, doc.get(FIELDNAME));
		assertEquals(elementId, doc.get(IIndexElement.FIELD_ID));
		assertEquals(INDEX_TYPE, doc.get(IIndexElement.FIELD_INDEX_TYPE));
	}
}
 
开发者ID:XMBomb,项目名称:InComb,代码行数:21,代码来源:IndexingThreadTest.java

示例9: createMultiDocumentSearcher

import org.apache.lucene.search.IndexSearcher; //导入依赖的package包/类
static IndexSearcher createMultiDocumentSearcher(Analyzer analyzer, ParsedDocument doc) {
    RAMDirectory ramDirectory = new RAMDirectory();
    try (IndexWriter indexWriter = new IndexWriter(ramDirectory, new IndexWriterConfig(analyzer))) {
        indexWriter.addDocuments(doc.docs());
        indexWriter.commit();
        DirectoryReader directoryReader = DirectoryReader.open(ramDirectory);
        assert directoryReader.leaves().size() == 1 : "Expected single leaf, but got [" + directoryReader.leaves().size() + "]";
        final IndexSearcher slowSearcher = new IndexSearcher(directoryReader) {

            @Override
            public Weight createNormalizedWeight(Query query, boolean needsScores) throws IOException {
                BooleanQuery.Builder bq = new BooleanQuery.Builder();
                bq.add(query, BooleanClause.Occur.MUST);
                bq.add(Queries.newNestedFilter(), BooleanClause.Occur.MUST_NOT);
                return super.createNormalizedWeight(bq.build(), needsScores);
            }

        };
        slowSearcher.setQueryCache(null);
        return slowSearcher;
    } catch (IOException e) {
        throw new ElasticsearchException("Failed to create index for percolator with nested document ", e);
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:25,代码来源:PercolateQueryBuilder.java

示例10: createIndexSearch

import org.apache.lucene.search.IndexSearcher; //导入依赖的package包/类
/**
	 * 初始化indexSearch对象的方法
	 * @throws Exception
	 */
	public void createIndexSearch(){
		try{
			IndexReader indexReader = DirectoryReader.open(this.indexSettings.directory);
			this.indexSearcher = new IndexSearcher(indexReader);
			//输出现在的索引
//	        for(int i =0; i<indexReader.numDocs();i++){
//	        	System.out.println(indexReader.document(i));
//	        	System.out.println("文件名称:"+indexReader.document(i).get("fileName")+"\t文件描述:"+indexReader.document(i).get("fileDesc")+"\t文件ID:"+indexReader.document(i).get("fileId")+"\t创建者:"+indexReader.document(i).get("fileCreator"));
//	        }
//	        System.out.println("索引版本:" + indexReader.getCoreCacheKey());
//	    	System.out.println("索引内文档数量:"+indexReader.numDocs());
		}catch(Exception e){
			e.printStackTrace();
		}
	}
 
开发者ID:zhangjikai,项目名称:sdudoc,代码行数:20,代码来源:LuceneIndexSearch.java

示例11: reset

import org.apache.lucene.search.IndexSearcher; //导入依赖的package包/类
@PostConstruct
public void reset() {
    final String dirPath = appConfig.getAllIndexDir();
    try {
        Directory directory = FSDirectory.open(new File(dirPath));
        if (!IndexReader.indexExists(directory)) {
            logger.error("Please reset index firstly! The path: {}", dirPath);
            return;
        }
        Directory ram = new RAMDirectory(directory);
        if (this.indexReader == null) {
            reopenIndexSearcher(ram);
        } else {
            // changed
            logger.info("Search's new indexReader!");
            final IndexReader preIndexReader = this.indexReader;
            final IndexSearcher preIndexSearcher = this.indexSearcher;
            reopenIndexSearcher(ram);
            IOUtils.closeQuietly(preIndexSearcher, preIndexReader);
            logger.info("Reload search index!");
        }
        logger.info("Search's IndexReader has numDos: {}", this.indexReader.numDocs());
    } catch (Exception e) {
        logger.error("Exception", e);
    }
}
 
开发者ID:zhaoxi1988,项目名称:sjk,代码行数:27,代码来源:SearchService1Impl.java

示例12: synTokenQuery

import org.apache.lucene.search.IndexSearcher; //导入依赖的package包/类
private void synTokenQuery(String search, final int numbOfResults, final double minLuceneScore,
		Map<String, Float> result, IndexSearcher searcher) throws ParseException, IOException {

	QueryParser parser = new QueryParser(Version.LUCENE_46, "surfaceFormTokens",
			new StandardAnalyzer(Version.LUCENE_46));

	search = QueryParser.escape(search);

	Query q = parser.parse(search);
	/*
	 * Works only in String field!!
	 */
	// Query q = new FuzzyQuery(new Term("surfaceFormTokens",
	// QueryParser.escape(search)), 2);

	TopDocs top = searcher.search(q, numbOfResults);

	for (ScoreDoc doc : top.scoreDocs) {
		if (doc.score >= minLuceneScore) {
			final String key = searcher.doc(doc.doc).get("conceptID");
			if (result.getOrDefault(key, 0f) < doc.score) {
				result.put(key, doc.score);
			}
		}
	}
}
 
开发者ID:ag-sc,项目名称:JLink,代码行数:27,代码来源:LuceneRetrieval.java

示例13: testVectorHighlighterNoTermVector

import org.apache.lucene.search.IndexSearcher; //导入依赖的package包/类
public void testVectorHighlighterNoTermVector() throws Exception {
    Directory dir = new RAMDirectory();
    IndexWriter indexWriter = new IndexWriter(dir, new IndexWriterConfig(Lucene.STANDARD_ANALYZER));

    Document document = new Document();
    document.add(new TextField("_id", "1", Field.Store.YES));
    document.add(new TextField("content", "the big bad dog", Field.Store.YES));
    indexWriter.addDocument(document);

    IndexReader reader = DirectoryReader.open(indexWriter);
    IndexSearcher searcher = new IndexSearcher(reader);
    TopDocs topDocs = searcher.search(new TermQuery(new Term("_id", "1")), 1);

    assertThat(topDocs.totalHits, equalTo(1));

    FastVectorHighlighter highlighter = new FastVectorHighlighter();
    String fragment = highlighter.getBestFragment(highlighter.getFieldQuery(new TermQuery(new Term("content", "bad"))),
            reader, topDocs.scoreDocs[0].doc, "content", 30);
    assertThat(fragment, nullValue());
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:21,代码来源:VectorHighlighterTests.java

示例14: innerExecute

import org.apache.lucene.search.IndexSearcher; //导入依赖的package包/类
@Override
public TermSuggestion innerExecute(String name, TermSuggestionContext suggestion, IndexSearcher searcher, CharsRefBuilder spare)
        throws IOException {
    DirectSpellChecker directSpellChecker = suggestion.getDirectSpellCheckerSettings().createDirectSpellChecker();
    final IndexReader indexReader = searcher.getIndexReader();
    TermSuggestion response = new TermSuggestion(
            name, suggestion.getSize(), suggestion.getDirectSpellCheckerSettings().sort()
    );
    List<Token> tokens = queryTerms(suggestion, spare);
    for (Token token : tokens) {
        // TODO: Extend DirectSpellChecker in 4.1, to get the raw suggested words as BytesRef
        SuggestWord[] suggestedWords = directSpellChecker.suggestSimilar(
                token.term, suggestion.getShardSize(), indexReader, suggestion.getDirectSpellCheckerSettings().suggestMode()
        );
        Text key = new Text(new BytesArray(token.term.bytes()));
        TermSuggestion.Entry resultEntry = new TermSuggestion.Entry(key, token.startOffset, token.endOffset - token.startOffset);
        for (SuggestWord suggestWord : suggestedWords) {
            Text word = new Text(suggestWord.string);
            resultEntry.addOption(new TermSuggestion.Entry.Option(word, suggestWord.freq, suggestWord.score));
        }
        response.addTerm(resultEntry);
    }
    return response;
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:25,代码来源:TermSuggester.java

示例15: createWeight

import org.apache.lucene.search.IndexSearcher; //导入依赖的package包/类
@Override
public Weight createWeight(IndexSearcher searcher, boolean needsScores) throws IOException {
    return new RandomAccessWeight(this) {
        @Override
        protected Bits getMatchingDocs(final LeafReaderContext context) throws IOException {
            final SortedNumericDocValues values = DocValues.getSortedNumeric(context.reader(), getField());
            return new Bits() {
                @Override
                public boolean get(int doc) {
                    values.setDocument(doc);
                    for (int i = 0; i < values.count(); i++) {
                        return contains(BitMixer.mix(values.valueAt(i)));
                    }
                    return contains(0);
                }

                @Override
                public int length() {
                    return context.reader().maxDoc();
                }
            };
        }
    };
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:25,代码来源:DocValuesSliceQuery.java


注:本文中的org.apache.lucene.search.IndexSearcher类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。