当前位置: 首页>>代码示例>>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;未经允许,请勿转载。