當前位置: 首頁>>代碼示例>>Java>>正文


Java Query類代碼示例

本文整理匯總了Java中org.apache.lucene.search.Query的典型用法代碼示例。如果您正苦於以下問題:Java Query類的具體用法?Java Query怎麽用?Java Query使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Query類屬於org.apache.lucene.search包,在下文中一共展示了Query類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: test_QParserGetsCalled

import org.apache.lucene.search.Query; //導入依賴的package包/類
/**
 * Basic test that checks that the "/similarity-query"
 * defined in the resources/solrconfig.xml does set the query parser
 * to the <code>{@link SimilarityParserPlugin}</code>
 */
public void test_QParserGetsCalled() throws Exception {

    // arrange
    SolrQueryRequest queryRequest = req("testQueryString");

    // act
    SolrQueryResponse resp = h.queryAndResponse("/similarity-query", queryRequest);

    // assert - the only way to check that the similarity parser was used is to check
    //          the type of the query returned by the similarity parser (for a single term): AugmentedTermQuery
    BasicResultContext basicResultContext = (BasicResultContext)resp.getResponse();
    Query usedLuceneQuery = basicResultContext.getQuery();
    assertTrue(usedLuceneQuery instanceof AugmentedTermQuery);

    // cleanup
    queryRequest.close();
}
 
開發者ID:sebastian-hofstaetter,項目名稱:ir-generalized-translation-models,代碼行數:23,代碼來源:SimilarityParserPluginIntegrationTest.java

示例2: testAnalyzeWildcard

import org.apache.lucene.search.Query; //導入依賴的package包/類
public void testAnalyzeWildcard() {
    SimpleQueryParser.Settings settings = new SimpleQueryParser.Settings();
    settings.analyzeWildcard(true);
    Map<String, Float> weights = new HashMap<>();
    weights.put("field1", 1.0f);
    SimpleQueryParser parser = new MockSimpleQueryParser(new StandardAnalyzer(), weights, -1, settings);
    for (Operator op : Operator.values()) {
        BooleanClause.Occur defaultOp = op.toBooleanClauseOccur();
        parser.setDefaultOperator(defaultOp);
        Query query = parser.parse("first foo-bar-foobar* last");
        Query expectedQuery =
            new BooleanQuery.Builder()
                .add(new BooleanClause(new TermQuery(new Term("field1", "first")), defaultOp))
                .add(new BooleanQuery.Builder()
                    .add(new BooleanClause(new TermQuery(new Term("field1", "foo")), defaultOp))
                    .add(new BooleanClause(new TermQuery(new Term("field1", "bar")), defaultOp))
                    .add(new BooleanClause(new PrefixQuery(new Term("field1", "foobar")), defaultOp))
                    .build(), defaultOp)
                .add(new BooleanClause(new TermQuery(new Term("field1", "last")), defaultOp))
                .build();
        assertThat(query, equalTo(expectedQuery));
    }
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:24,代碼來源:SimpleQueryParserTests.java

示例3: getQuery

import org.apache.lucene.search.Query; //導入依賴的package包/類
@Override
public Query getQuery(Element e) throws ParserException {
  float tieBreaker = DOMUtils.getAttribute(e, "tieBreaker", 0.0f); 
  DisjunctionMaxQuery dq = new DisjunctionMaxQuery(tieBreaker);
  dq.setBoost(DOMUtils.getAttribute(e, "boost", 1.0f));

  NodeList nl = e.getChildNodes();
  for (int i = 0; i < nl.getLength(); i++) {
    Node node = nl.item(i);
    if (node instanceof Element) { // all elements are disjuncts.
      Element queryElem = (Element) node;
      Query q = factory.getQuery(queryElem);
      dq.add(q);
    }
  }

  return dq;
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:19,代碼來源:DisjunctionMaxQueryBuilder.java

示例4: loadQueries

import org.apache.lucene.search.Query; //導入依賴的package包/類
private int loadQueries(IndexShard shard) {
    shard.refresh("percolator_load_queries");
    // NOTE: we acquire the searcher via the engine directly here since this is executed right
    // before the shard is marked as POST_RECOVERY
    try (Engine.Searcher searcher = shard.engine().acquireSearcher("percolator_load_queries")) {
        Query query = new TermQuery(new Term(TypeFieldMapper.NAME, PercolatorService.TYPE_NAME));
        QueriesLoaderCollector queryCollector = new QueriesLoaderCollector(PercolatorQueriesRegistry.this, logger, mapperService, indexFieldDataService);
        IndexSearcher indexSearcher = new IndexSearcher(searcher.reader());
        indexSearcher.setQueryCache(null);
        indexSearcher.search(query, queryCollector);
        Map<BytesRef, Query> queries = queryCollector.queries();
        for (Map.Entry<BytesRef, Query> entry : queries.entrySet()) {
            Query previousQuery = percolateQueries.put(entry.getKey(), entry.getValue());
            shardPercolateService.addedQuery(entry.getKey(), previousQuery, entry.getValue());
        }
        return queries.size();
    } catch (Exception e) {
        throw new PercolatorException(shardId.index(), "failed to load queries from percolator index", e);
    }
}
 
開發者ID:baidu,項目名稱:Elasticsearch,代碼行數:21,代碼來源:PercolatorQueriesRegistry.java

示例5: rewrite

import org.apache.lucene.search.Query; //導入依賴的package包/類
@Override
public Query rewrite(IndexReader reader) throws IOException {
  SpanNotQuery clone = null;

  SpanQuery rewrittenInclude = (SpanQuery) include.rewrite(reader);
  if (rewrittenInclude != include) {
    clone = this.clone();
    clone.include = rewrittenInclude;
  }
  SpanQuery rewrittenExclude = (SpanQuery) exclude.rewrite(reader);
  if (rewrittenExclude != exclude) {
    if (clone == null) clone = this.clone();
    clone.exclude = rewrittenExclude;
  }

  if (clone != null) {
    return clone;                        // some clauses rewrote
  } else {
    return this;                         // no clauses rewrote
  }
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:22,代碼來源:SpanNotQuery.java

示例6: prefixSearch

import org.apache.lucene.search.Query; //導入依賴的package包/類
@Override
public ScoreDoc[] prefixSearch(String q) throws IOException {
    if (StringUtils.isEmpty(q) || q.length() > appConfig.getKeywordMaxLength()) {
        logger.error("empty keywords or over-length! {}", q);
        return null;
    }

    final TopDocs[] rstTopDocs = new TopDocs[2];
    final Query nameFldQuery = new PrefixQuery(new Term(NAME.getName(), q));
    rstTopDocs[0] = indexSearcher.search(nameFldQuery, appConfig.getQuickTipsNum() * 2, sort);

    final Query downLoadRankQuery = NumericRangeQuery.newIntRange(DOWNOLOAD_RANK.getName(), MIN_DOWNLOAD_RANK,
            Integer.MAX_VALUE, true, false);
    // 從下載量最高的1000條記錄中,再過濾符合關鍵字的記錄
    rstTopDocs[1] = indexSearcher.search(downLoadRankQuery, MAX_TOP, sort);
    TopDocs rst = TopDocsUtil.mergeDuplicateDocId(TopDocs.merge(sort, MAX_TOP + appConfig.getQuickTipsNum() * 2,
            rstTopDocs));
    if (rst != null) {
        return rst.scoreDocs;
    }
    return null;
}
 
開發者ID:zhaoxi1988,項目名稱:sjk,代碼行數:23,代碼來源:QuickTipsService1Impl.java

示例7: exists

import org.apache.lucene.search.Query; //導入依賴的package包/類
/**
 * Check whether there is one or more documents matching the provided query.
 */
public static boolean exists(IndexSearcher searcher, Query query) throws IOException {
    final Weight weight = searcher.createNormalizedWeight(query, false);
    // the scorer API should be more efficient at stopping after the first
    // match than the bulk scorer API
    for (LeafReaderContext context : searcher.getIndexReader().leaves()) {
        final Scorer scorer = weight.scorer(context);
        if (scorer == null) {
            continue;
        }
        final Bits liveDocs = context.reader().getLiveDocs();
        final DocIdSetIterator iterator = scorer.iterator();
        for (int doc = iterator.nextDoc(); doc != DocIdSetIterator.NO_MORE_DOCS; doc = iterator.nextDoc()) {
            if (liveDocs == null || liveDocs.get(doc)) {
                return true;
            }
        }
    }
    return false;
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:23,代碼來源:Lucene.java

示例8: findNestedObjectMapper

import org.apache.lucene.search.Query; //導入依賴的package包/類
/**
 * Returns the best nested {@link ObjectMapper} instances that is in the scope of the specified nested docId.
 */
public ObjectMapper findNestedObjectMapper(int nestedDocId, SearchContext sc, LeafReaderContext context) throws IOException {
    ObjectMapper nestedObjectMapper = null;
    for (ObjectMapper objectMapper : objectMappers().values()) {
        if (!objectMapper.nested().isNested()) {
            continue;
        }

        Query filter = objectMapper.nestedTypeFilter();
        if (filter == null) {
            continue;
        }
        // We can pass down 'null' as acceptedDocs, because nestedDocId is a doc to be fetched and
        // therefor is guaranteed to be a live doc.
        final Weight nestedWeight = filter.createWeight(sc.searcher(), false);
        Scorer scorer = nestedWeight.scorer(context);
        if (scorer == null) {
            continue;
        }

        if (scorer.iterator().advance(nestedDocId) == nestedDocId) {
            if (nestedObjectMapper == null) {
                nestedObjectMapper = objectMapper;
            } else {
                if (nestedObjectMapper.fullPath().length() < objectMapper.fullPath().length()) {
                    nestedObjectMapper = objectMapper;
                }
            }
        }
    }
    return nestedObjectMapper;
}
 
開發者ID:baidu,項目名稱:Elasticsearch,代碼行數:35,代碼來源:DocumentMapper.java

示例9: doToQuery

import org.apache.lucene.search.Query; //導入依賴的package包/類
@Override
protected Query doToQuery(QueryShardContext context) throws IOException {
    if (termsLookup != null) {
        throw new UnsupportedOperationException("query must be rewritten first");
    }
    if (values == null || values.isEmpty()) {
        return Queries.newMatchNoDocsQuery("No terms supplied for \"" + getName() + "\" query.");
    }
    MappedFieldType fieldType = context.fieldMapper(fieldName);

    if (fieldType != null) {
        return fieldType.termsQuery(values, context);
    } else {
        BytesRef[] filterValues = new BytesRef[values.size()];
        for (int i = 0; i < filterValues.length; i++) {
            filterValues[i] = BytesRefs.toBytesRef(values.get(i));
        }
        return new TermInSetQuery(fieldName, filterValues);
    }
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:21,代碼來源:TermsQueryBuilder.java

示例10: FreqTermsEnum

import org.apache.lucene.search.Query; //導入依賴的package包/類
public FreqTermsEnum(IndexReader reader, String field, boolean needDocFreq, boolean needTotalTermFreq, @Nullable Query filter, BigArrays bigArrays) throws IOException {
    super(reader, field, needTotalTermFreq ? PostingsEnum.FREQS : PostingsEnum.NONE, filter);
    this.bigArrays = bigArrays;
    this.needDocFreqs = needDocFreq;
    this.needTotalTermFreqs = needTotalTermFreq;
    if (needDocFreq) {
        termDocFreqs = bigArrays.newIntArray(INITIAL_NUM_TERM_FREQS_CACHED, false);
    } else {
        termDocFreqs = null;
    }
    if (needTotalTermFreq) {
        termsTotalFreqs = bigArrays.newLongArray(INITIAL_NUM_TERM_FREQS_CACHED, false);
    } else {
        termsTotalFreqs = null;
    }
    cachedTermOrds = new BytesRefHash(INITIAL_NUM_TERM_FREQS_CACHED, bigArrays);
}
 
開發者ID:baidu,項目名稱:Elasticsearch,代碼行數:18,代碼來源:FreqTermsEnum.java

示例11: searchIndex

import org.apache.lucene.search.Query; //導入依賴的package包/類
/**
 * 查詢索引
 * 
 * @param keywords
 * @return
 * @throws Exception
 */
public List<Document> searchIndex(Integer typeId, String keywords) throws Exception {
    // 1.init searcher
    Analyzer analyzer = new PaodingAnalyzer();
    IndexReader reader = IndexReader.open(typeId == appConfig.getGameTypeId() ? appConfig.getGameIndexDir()
            : appConfig.getSoftIndexDir());
    BooleanClause.Occur[] flags = new BooleanClause.Occur[] { BooleanClause.Occur.SHOULD,
            BooleanClause.Occur.SHOULD };
    Query query = MultiFieldQueryParser.parse(keywords, appConfig.getQueryFields(), flags, analyzer);
    query = query.rewrite(reader);

    // 2.search
    List<Document> docs = new ArrayList<Document>();
    Hits hits = (typeId == appConfig.getGameTypeId() ? gameSearcher.search(query, Sort.RELEVANCE) : softSearcher
            .search(query, Sort.RELEVANCE));// searcher.search(query,
                                            // Sort.RELEVANCE);
    for (int i = 0; i < hits.length(); i++) {
        docs.add(hits.doc(i));
    }

    // 3.return
    reader.close();
    return docs;
}
 
開發者ID:zhaoxi1988,項目名稱:sjk,代碼行數:31,代碼來源:SearchServiceImpl.java

示例12: applySlop

import org.apache.lucene.search.Query; //導入依賴的package包/類
private Query applySlop(Query q, int slop) {
    if (q instanceof PhraseQuery) {
        PhraseQuery pq = (PhraseQuery) q;
        PhraseQuery.Builder builder = new PhraseQuery.Builder();
        builder.setSlop(slop);
        final Term[] terms = pq.getTerms();
        final int[] positions = pq.getPositions();
        for (int i = 0; i < terms.length; ++i) {
            builder.add(terms[i], positions[i]);
        }
        pq = builder.build();
        pq.setBoost(q.getBoost());
        return pq;
    } else if (q instanceof MultiPhraseQuery) {
        ((MultiPhraseQuery) q).setSlop(slop);
        return q;
    } else {
        return q;
    }
}
 
開發者ID:baidu,項目名稱:Elasticsearch,代碼行數:21,代碼來源:MapperQueryParser.java

示例13: getFTSQuery

import org.apache.lucene.search.Query; //導入依賴的package包/類
@Override
public FullTextQuery getFTSQuery(String filterText, final Class<?> entityType, Integer maxResults, String... fields) {

	// entityManager para busquedas de tipo FTS
	final FullTextEntityManager fullTextEntityManager = org.hibernate.search.jpa.Search.getFullTextEntityManager(entityManager);

	// se crea el query usando Hibernate Search query DSL
	final QueryBuilder queryBuilder = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(entityType).get();

	// se crea el query sobre los campos indicados
	final Query query = queryBuilder.keyword().onFields(fields).matching(filterText.trim()).createQuery();

	// se enmascara el query de Lucene en uno de Hibernate
	final FullTextQuery jpaQuery = fullTextEntityManager.createFullTextQuery(query, entityType);

	// se define la cantidad maxima de resultados si es mayor a cero
	if (maxResults > 0) {
		jpaQuery.setMaxResults(maxResults);
	}
	// se retorna el query listo para ejecución o para inyeccion de criterias
	return jpaQuery;
}
 
開發者ID:allianzit,項目名稱:ait-platform,代碼行數:23,代碼來源:AitFTSRepo.java

示例14: qsParsed

import org.apache.lucene.search.Query; //導入依賴的package包/類
static Query qsParsed(String query) {
	if (StringUtils.isBlank(query) || "*".equals(query.trim())) {
		return null;
	}
	try {
		StandardQueryParser parser = new StandardQueryParser();
		parser.setAllowLeadingWildcard(false);
		return parser.parse(query, "");
	} catch (Exception ex) {
		logger.warn("Failed to parse query string '{}'.", query);
	}
	return null;
}
 
開發者ID:Erudika,項目名稱:para-search-elasticsearch,代碼行數:14,代碼來源:ElasticSearchUtils.java

示例15: rangeQuery

import org.apache.lucene.search.Query; //導入依賴的package包/類
@Override
public Query rangeQuery(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, QueryShardContext context) {
    failIfNotIndexed();
    return new TermRangeQuery(name(),
        lowerTerm == null ? null : indexedValueForSearch(lowerTerm),
        upperTerm == null ? null : indexedValueForSearch(upperTerm),
        includeLower, includeUpper);
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:9,代碼來源:StringFieldType.java


注:本文中的org.apache.lucene.search.Query類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。