Java 类org.apache.lucene.search.PrefixQuery 实例源码

项目:incubator-netbeans    文件:DocumentUtil.java   
private static BooleanQuery createFQNQuery(final String resourceName) {
    String pkgName;
    String sName;
    int index = resourceName.lastIndexOf(BinaryName.PKG_SEPARATOR);
    if (index < 0) {
        pkgName = "";       //NOI18N
        sName = resourceName;
    } else {
        pkgName = resourceName.substring(0, index);
        sName = resourceName.substring(index+1);
    }
    final BooleanQuery snQuery = new BooleanQuery();
    snQuery.add (new WildcardQuery (new Term (DocumentUtil.FIELD_BINARY_NAME, sName + DocumentUtil.WILDCARD_QUERY_WILDCARD)),Occur.SHOULD);
    snQuery.add (new PrefixQuery (new Term (DocumentUtil.FIELD_BINARY_NAME, sName + '$')),Occur.SHOULD);   //NOI18N
    if (pkgName.length() == 0) {
        return snQuery;
    }
    final BooleanQuery fqnQuery = new BooleanQuery();
    fqnQuery.add(new TermQuery(new Term(DocumentUtil.FIELD_PACKAGE_NAME,pkgName)), Occur.MUST);
    fqnQuery.add(snQuery, Occur.MUST);
    return fqnQuery;
}
项目:InComb    文件:QueryUtil.java   
/**
 * Adds for every field in {@link IIndexTypeConf} a {@link TermQuery}, {@link PrefixQuery} and
 * a {@link FuzzyQuery} with a suitable boost relative to the given base boost.
 *
 * @param indexType the type in which should be searched.
 * @param search the search text.
 * @param subQuery the {@link BooleanQuery} to add the sub queries.
 * @param baseBoost highest possible boost of the query. The more the match is exact
 *          than a bigger boost will be used.
 */
private static void addSearchTermQueries(final IIndexTypeConf indexType, final String search,
        final BooleanQuery subQuery, final float baseBoost) {

    for(final IIndexFieldConf<?> field : indexType.getFields()) {
        final Term term = new Term(field.getName(), search);

        final TermQuery exactQuery = new TermQuery(term);
        exactQuery.setBoost(baseBoost);
        subQuery.add(exactQuery, Occur.SHOULD);

        final PrefixQuery pfQuery = new PrefixQuery(term);
        pfQuery.setBoost(0.7f*baseBoost);
        subQuery.add(pfQuery, Occur.SHOULD);

        final FuzzyQuery fuzzyQuery = new FuzzyQuery(term);
        fuzzyQuery.setBoost(0.5f*baseBoost);
        subQuery.add(fuzzyQuery, Occur.SHOULD);
    }
}
项目:elasticsearch_my    文件:SimpleQueryParser.java   
/**
 * Dispatches to Lucene's SimpleQueryParser's newPrefixQuery, optionally
 * lowercasing the term first or trying to analyze terms
 */
@Override
public Query newPrefixQuery(String text) {
    BooleanQuery.Builder bq = new BooleanQuery.Builder();
    bq.setDisableCoord(true);
    for (Map.Entry<String,Float> entry : weights.entrySet()) {
        final String fieldName = entry.getKey();
        try {
            if (settings.analyzeWildcard()) {
                Query analyzedQuery = newPossiblyAnalyzedQuery(fieldName, text);
                if (analyzedQuery != null) {
                    bq.add(wrapWithBoost(analyzedQuery, entry.getValue()), BooleanClause.Occur.SHOULD);
                }
            } else {
                Term term = new Term(fieldName, getAnalyzer().normalize(fieldName, text));
                Query query = new PrefixQuery(term);
                bq.add(wrapWithBoost(query, entry.getValue()), BooleanClause.Occur.SHOULD);
            }
        } catch (RuntimeException e) {
            return rethrowUnlessLenient(e);
        }
    }
    return super.simplify(bq.build());
}
项目:elasticsearch_my    文件:SimpleQueryParserTests.java   
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));
    }
}
项目:NGB-master    文件:VcfFilterForm.java   
private void addGeneFilter(BooleanQuery.Builder builder) {
    if (genes != null && !genes.field.isEmpty()) {
        BooleanQuery.Builder genesBuilder = new BooleanQuery.Builder();
        for (int i = 0; i < genes.field.size(); i++) {
            PrefixQuery geneIdPrefixQuery = new PrefixQuery(new Term(FeatureIndexFields.GENE_ID.getFieldName(),
                    genes.field.get(i).toLowerCase()));
            PrefixQuery geneNamePrefixQuery = new PrefixQuery(
                new Term(FeatureIndexFields.GENE_NAME.getFieldName(), genes.field.get(i).toLowerCase()));
            BooleanQuery.Builder geneIdOrNameQuery = new BooleanQuery.Builder();
            geneIdOrNameQuery.add(geneIdPrefixQuery, BooleanClause.Occur.SHOULD);
            geneIdOrNameQuery.add(geneNamePrefixQuery, BooleanClause.Occur.SHOULD);

            genesBuilder.add(geneIdOrNameQuery.build(), genes.conjunction ? BooleanClause.Occur.MUST :
                    BooleanClause.Occur.SHOULD);
        }

        builder.add(genesBuilder.build(), BooleanClause.Occur.MUST);
    }
}
项目:sjk    文件:QuickTipsServiceImpl.java   
@Override
public ScoreDoc[] prefixSearch(String keywords) throws IOException {
    if (StringUtils.isEmpty(keywords) || keywords.length() > appConfig.getKeywordMaxLength()) {
        logger.error("empty keywords or over-length! {}", keywords);
        return null;
    }
    Sort sort = new Sort(new SortField("downloadRank", SortField.INT, true));

    Term nameFldTerm = new Term(fieldName, keywords);
    PrefixQuery nameFldQuery = new PrefixQuery(nameFldTerm);

    NumericRangeQuery<Integer> catalogQuery = NumericRangeQuery.newIntRange("catalog",
            (int) EnumCatalog.SOFT.getCatalog(), (int) EnumCatalog.GAME.getCatalog(), true, true);
    BooleanQuery booleanQuery = new BooleanQuery();
    booleanQuery.add(catalogQuery, Occur.MUST);
    booleanQuery.add(nameFldQuery, Occur.MUST);

    TopDocs topDocs = quickTipsSearcher.search(booleanQuery, appConfig.getQuickTipsNum() * 2, sort);
    ScoreDoc[] docs = topDocs.scoreDocs;
    return docs;
}
项目:sjk    文件:QuickTipsService1Impl.java   
@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;
}
项目:sjk    文件:QuickTipsServiceImpl.java   
@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;
}
项目:NGB    文件:VcfFilterForm.java   
private void addGeneFilter(BooleanQuery.Builder builder) {
    if (genes != null && !genes.field.isEmpty()) {
        BooleanQuery.Builder genesBuilder = new BooleanQuery.Builder();
        for (int i = 0; i < genes.field.size(); i++) {
            PrefixQuery geneIdPrefixQuery = new PrefixQuery(new Term(FeatureIndexFields.GENE_ID.getFieldName(),
                    genes.field.get(i).toLowerCase()));
            PrefixQuery geneNamePrefixQuery = new PrefixQuery(
                new Term(FeatureIndexFields.GENE_NAME.getFieldName(), genes.field.get(i).toLowerCase()));
            BooleanQuery.Builder geneIdOrNameQuery = new BooleanQuery.Builder();
            geneIdOrNameQuery.add(geneIdPrefixQuery, BooleanClause.Occur.SHOULD);
            geneIdOrNameQuery.add(geneNamePrefixQuery, BooleanClause.Occur.SHOULD);

            genesBuilder.add(geneIdOrNameQuery.build(), genes.conjunction ? BooleanClause.Occur.MUST :
                    BooleanClause.Occur.SHOULD);
        }

        builder.add(genesBuilder.build(), BooleanClause.Occur.MUST);
    }
}
项目:wikisearch    文件:LuceneSearchCommand.java   
@Override
public void execute(boolean interactive) throws CommandException {
    logger.debug("Executing search command");
    try (IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(indexPath)))) {
        IndexSearcher searcher = new IndexSearcher(reader);
        QueryParser queryParser = new QueryParser("contents", new StandardAnalyzer());
        BooleanQuery booleanQuery = new BooleanQuery.Builder()
                .add(new PrefixQuery(new Term("contributor", queryString)), BooleanClause.Occur.SHOULD)
                .add(queryParser.parse(String.format("%s*", queryString)), BooleanClause.Occur.SHOULD).build();
        doPagingSearch(new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8)), searcher,
                booleanQuery, 10, interactive);

    } catch (IOException | ParseException e) {
        logger.error("Exception while executing search command.", e);
        throw new CommandException("Error while executing command. Excution failed.", e);
    }

}
项目:search    文件:TestSpanMultiTermQueryWrapper.java   
public void testNoSuchMultiTermsInSpanFirst() throws Exception {
  //this hasn't been a problem  
  FuzzyQuery fuzzyNoSuch = new FuzzyQuery(new Term("field", "noSuch"), 1, 0, 1, false);
  SpanQuery spanNoSuch = new SpanMultiTermQueryWrapper<>(fuzzyNoSuch);
  SpanQuery spanFirst = new SpanFirstQuery(spanNoSuch, 10);

  assertEquals(0, searcher.search(spanFirst, 10).totalHits);

  WildcardQuery wcNoSuch = new WildcardQuery(new Term("field", "noSuch*"));
  SpanQuery spanWCNoSuch = new SpanMultiTermQueryWrapper<>(wcNoSuch);
  spanFirst = new SpanFirstQuery(spanWCNoSuch, 10);
  assertEquals(0, searcher.search(spanFirst, 10).totalHits);

  RegexpQuery rgxNoSuch = new RegexpQuery(new Term("field", "noSuch"));
  SpanQuery spanRgxNoSuch = new SpanMultiTermQueryWrapper<>(rgxNoSuch);
  spanFirst = new SpanFirstQuery(spanRgxNoSuch, 10);
  assertEquals(0, searcher.search(spanFirst, 10).totalHits);

  PrefixQuery prfxNoSuch = new PrefixQuery(new Term("field", "noSuch"));
  SpanQuery spanPrfxNoSuch = new SpanMultiTermQueryWrapper<>(prfxNoSuch);
  spanFirst = new SpanFirstQuery(spanPrfxNoSuch, 10);
  assertEquals(0, searcher.search(spanFirst, 10).totalHits);
}
项目:eHMP    文件:LOINCSearchFrame.java   
/**
 * Enhancements: match any LOINC term (includes synonyms)? permit any loinc code (not just chemistries)
 * @param search
 * @return
 */
private Map<String,String> getLOINCMatches(String search) {
    // try to match the search terms against a narrow portion of the LOINC higherarchy
    BooleanQuery q1 = new BooleanQuery();
    q1.add(new TermQuery(new Term("parent", LNC_CHEM)), BooleanClause.Occur.MUST);
    q1.add(new PrefixQuery(new Term("term", search)), BooleanClause.Occur.MUST);

    // match any exact loinc code
    BooleanQuery q2 = new BooleanQuery();
    q2.add(new TermQuery(new Term("sab", "lnc")), BooleanClause.Occur.MUST);
    q2.add(new TermQuery(new Term("code", search)), BooleanClause.Occur.MUST);

    BooleanQuery q = new BooleanQuery();
    q.add(q1, BooleanClause.Occur.SHOULD);
    q.add(q2, BooleanClause.Occur.SHOULD);

    Map<String,String> ret = new HashMap<>();
    for (String urn : eng.search(q)) {
        String desc = eng.getDescription(urn);
        ret.put(urn, desc);
    }
    return ret;
}
项目:imcms    文件:LinkCheck.java   
private void addTextAndImageLinks(List<Link> links, DocumentIndex reindexingIndex, UserDomainObject user,
                                  HttpServletRequest request, IntRange range) {
    BooleanQuery query = new BooleanQuery();
    query.add(new PrefixQuery(new Term(DocumentIndex.FIELD__NONSTRIPPED_TEXT, "http")), Occur.SHOULD);
    query.add(new PrefixQuery(new Term(DocumentIndex.FIELD__NONSTRIPPED_TEXT, "href")), Occur.SHOULD);
    query.add(new PrefixQuery(new Term(DocumentIndex.FIELD__IMAGE_LINK_URL, "http")), Occur.SHOULD);

    List textDocuments = reindexingIndex.search(new SimpleDocumentQuery(query), user);

    for (Object textDocument1 : textDocuments) {
        TextDocumentDomainObject textDocument = (TextDocumentDomainObject) textDocument1;
        if (!range.containsInteger(textDocument.getId())) {
            continue;
        }
        addTextLinks(links, textDocument, request);
        addImageLinks(links, textDocument, request);
    }
}
项目:imhotep    文件:LuceneQueryTranslator.java   
public static Query rewrite(org.apache.lucene.search.Query q, Set<String> intFields) {
    if (q instanceof TermQuery) {
        return rewrite((TermQuery)q, intFields);
    } else if (q instanceof BooleanQuery) {
        return rewrite((BooleanQuery)q, intFields);
    } else if (q instanceof RangeQuery) {
        return rewrite((RangeQuery)q, intFields);
    } else if (q instanceof ConstantScoreRangeQuery) {
        return rewrite((ConstantScoreRangeQuery)q, intFields);
    } else if (q instanceof PrefixQuery) {
        return rewrite((PrefixQuery)q, intFields);
    } else if (q instanceof PhraseQuery) {
        return rewrite((PhraseQuery)q, intFields);
    }
    throw new IllegalArgumentException("unsupported lucene query type: " + q.getClass().getSimpleName());
}
项目:stratio-cassandra    文件:PrefixConditionTest.java   
@Test
public void testString() {

    Map<String, ColumnMapper> map = new HashMap<>();
    map.put("name", new ColumnMapperString());
    Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName());

    PrefixCondition prefixCondition = new PrefixCondition(0.5f, "name", "tr");
    Query query = prefixCondition.query(mappers);

    Assert.assertNotNull(query);
    Assert.assertEquals(PrefixQuery.class, query.getClass());
    PrefixQuery luceneQuery = (PrefixQuery) query;
    Assert.assertEquals("name", luceneQuery.getField());
    Assert.assertEquals("tr", luceneQuery.getPrefix().text());
    Assert.assertEquals(0.5f, query.getBoost(), 0);
}
项目:stratio-cassandra    文件:PrefixConditionTest.java   
@Test
public void testInetV4() {

    Map<String, ColumnMapper> map = new HashMap<>();
    map.put("name", new ColumnMapperInet());
    Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName());

    PrefixCondition wildcardCondition = new PrefixCondition(0.5f, "name", "192.168.");
    Query query = wildcardCondition.query(mappers);

    Assert.assertNotNull(query);
    Assert.assertEquals(PrefixQuery.class, query.getClass());
    PrefixQuery luceneQuery = (PrefixQuery) query;
    Assert.assertEquals("name", luceneQuery.getField());
    Assert.assertEquals("192.168.", luceneQuery.getPrefix().text());
    Assert.assertEquals(0.5f, query.getBoost(), 0);
}
项目:stratio-cassandra    文件:PrefixConditionTest.java   
@Test
public void testInetV6() {

    Map<String, ColumnMapper> map = new HashMap<>();
    map.put("name", new ColumnMapperInet());
    Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName());

    PrefixCondition wildcardCondition = new PrefixCondition(0.5f, "name", "2001:db8:2de:0:0:0:0:e");
    Query query = wildcardCondition.query(mappers);

    Assert.assertNotNull(query);
    Assert.assertEquals(PrefixQuery.class, query.getClass());
    PrefixQuery luceneQuery = (PrefixQuery) query;
    Assert.assertEquals("name", luceneQuery.getField());
    Assert.assertEquals("2001:db8:2de:0:0:0:0:e", luceneQuery.getPrefix().text());
    Assert.assertEquals(0.5f, query.getBoost(), 0);
}
项目:NYBC    文件:TestFacetsPayloadMigrationReader.java   
private void verifyNotFacetsData(DirectoryReader indexReader, IndexSearcher searcher) throws IOException {
  // verify that non facets data was not damaged
  TotalHitCountCollector total = new TotalHitCountCollector();
  searcher.search(new PrefixQuery(new Term("foo", "content")), total);
  assertEquals("invalid number of results for content query", total.getTotalHits(), indexReader.maxDoc());

  int numDocIDs = 0;
  for (AtomicReaderContext context : indexReader.leaves()) {
    Terms docIDs = context.reader().terms("docid");
    assertNotNull(docIDs);
    TermsEnum te = docIDs.iterator(null);
    while (te.next() != null) {
      ++numDocIDs;
    }
  }
  assertEquals("invalid number of docid terms", indexReader.maxDoc(), numDocIDs);
}
项目:kha    文件:LuceneUsersDao.java   
@Override
public User findByOAuthAccessToken(String token) {
    LOGGER.info("Searching for user with OAuth2 access token '{}' in Lucene indexes", token);
    try {
        IndexSearcher indexSearcher = buildIndexSearcher();
        Term term = new Term(FIELD_OAUTH_TOKENS, token);
        BooleanQuery q = new BooleanQuery();
        q.add(new PrefixQuery(term), BooleanClause.Occur.MUST);
        q.add(new TermQuery(termType), BooleanClause.Occur.MUST);
        TopDocs hits = indexSearcher.search(q, 1);
        if (hits.totalHits == 0) {
            LOGGER.warn("No user found with OAuth access token '{}'", token);
            return null;            // no result found
        }
        ScoreDoc[] scoreDocs = hits.scoreDocs;
        ScoreDoc scoreDoc = scoreDocs[0];
        Document doc = indexSearcher.doc(scoreDoc.doc);
        return extractUserFromDoc(doc);
    } catch (IOException e) {
        LOGGER.error("Unexpected Lucene error", e);
        return null;
    }
}
项目:Maskana-Gestor-de-Conocimiento    文件:TestFacetsPayloadMigrationReader.java   
private void verifyNotFacetsData(DirectoryReader indexReader, IndexSearcher searcher) throws IOException {
  // verify that non facets data was not damaged
  TotalHitCountCollector total = new TotalHitCountCollector();
  searcher.search(new PrefixQuery(new Term("foo", "content")), total);
  assertEquals("invalid number of results for content query", total.getTotalHits(), indexReader.maxDoc());

  int numDocIDs = 0;
  for (AtomicReaderContext context : indexReader.leaves()) {
    Terms docIDs = context.reader().terms("docid");
    assertNotNull(docIDs);
    TermsEnum te = docIDs.iterator(null);
    while (te.next() != null) {
      ++numDocIDs;
    }
  }
  assertEquals("invalid number of docid terms", indexReader.maxDoc(), numDocIDs);
}
项目:netbeans-plugin    文件:QuerySupport.java   
Query createClassesQuery( String prefix, SourceType type, String fqn,
        Analyzer analyzer ) throws ParseException
{
    Query prefixQuery = new PrefixQuery(new Term(CLASS_NAME, prefix));
    Query typeQuery =
            new TermQuery(new Term(DOC_TYPE, DocType.CLASS.toString()));
    Query sourceType =
            new TermQuery(new Term(SOURCE_TYPE, type.toString()));
    BooleanQuery query = new BooleanQuery();
    query.add(prefixQuery, Occur.MUST);
    query.add(typeQuery, Occur.MUST);
    query.add(sourceType, Occur.MUST);
    if (fqn != null) {
        query.add(new TermQuery(new Term(CLASS_FQN, fqn)), Occur.MUST);
    }

    QueryParser parser =
            new QueryParser(Version.LUCENE_35, CLASS_NAME, analyzer);
    Query serchQuery = parser.parse(query.toString());
    return serchQuery;
}
项目:t4f-data    文件:PrefixQueryTest.java   
public void testPrefix() throws Exception {
  Directory dir = TestUtil.getBookIndexDirectory();
  IndexSearcher searcher = new IndexSearcher(dir);

  Term term = new Term("category",                              //#A
                       "/technology/computers/programming");    //#A
  PrefixQuery query = new PrefixQuery(term);                    //#A

  TopDocs matches = searcher.search(query, 10);                 //#A
  int programmingAndBelow = matches.totalHits;

  matches = searcher.search(new TermQuery(term), 10);           //#B
  int justProgramming = matches.totalHits;

  assertTrue(programmingAndBelow > justProgramming);
  searcher.close();
  dir.close();
}
项目:elasticsearch_my    文件:StringFieldType.java   
@Override
public final Query prefixQuery(String value, MultiTermQuery.RewriteMethod method, QueryShardContext context) {
    failIfNotIndexed();
    PrefixQuery query = new PrefixQuery(new Term(name(), indexedValueForSearch(value)));
    if (method != null) {
        query.setRewriteMethod(method);
    }
    return query;
}
项目:elasticsearch_my    文件:SimpleQueryParserTests.java   
public void testAnalyzerWildcardWithSynonyms() {
    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 MockRepeatAnalyzer(), 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 SynonymQuery(new Term("field1", "first"),
                new Term("field1", "first")), defaultOp))
            .add(new BooleanQuery.Builder()
                .add(new BooleanClause(new SynonymQuery(new Term("field1", "foo"),
                    new Term("field1", "foo")), defaultOp))
                .add(new BooleanClause(new SynonymQuery(new Term("field1", "bar"),
                    new Term("field1", "bar")), defaultOp))
                .add(new BooleanQuery.Builder()
                    .add(new BooleanClause(new PrefixQuery(new Term("field1", "foobar")),
                        BooleanClause.Occur.SHOULD))
                    .add(new BooleanClause(new PrefixQuery(new Term("field1", "foobar")),
                        BooleanClause.Occur.SHOULD))
                    .setDisableCoord(true)
                    .build(), defaultOp)
                .build(), defaultOp)
            .add(new BooleanClause(new SynonymQuery(new Term("field1", "last"),
                new Term("field1", "last")), defaultOp))
            .build();
        assertThat(query, equalTo(expectedQuery));
    }
}
项目:elasticsearch_my    文件:PrefixQueryBuilderTests.java   
@Override
protected void doAssertLuceneQuery(PrefixQueryBuilder queryBuilder, Query query, SearchContext context) throws IOException {
    assertThat(query, instanceOf(PrefixQuery.class));
    PrefixQuery prefixQuery = (PrefixQuery) query;
    assertThat(prefixQuery.getPrefix().field(), equalTo(queryBuilder.fieldName()));
    assertThat(prefixQuery.getPrefix().text(), equalTo(queryBuilder.value()));
}
项目:elasticsearch_my    文件:QueryStringQueryBuilderTests.java   
public void testToQueryWildcarQuery() throws Exception {
    assumeTrue("test runs only when at least a type is registered", getCurrentTypes().length > 0);
    for (Operator op : Operator.values()) {
        BooleanClause.Occur defaultOp = op.toBooleanClauseOccur();
        MapperQueryParser queryParser = new MapperQueryParser(createShardContext());
        QueryParserSettings settings = new QueryParserSettings("first foo-bar-foobar* last");
        settings.defaultField(STRING_FIELD_NAME);
        settings.fieldsAndWeights(Collections.emptyMap());
        settings.analyzeWildcard(true);
        settings.fuzziness(Fuzziness.AUTO);
        settings.rewriteMethod(MultiTermQuery.CONSTANT_SCORE_REWRITE);
        settings.defaultOperator(op.toQueryParserOperator());
        queryParser.reset(settings);
        Query query = queryParser.parse("first foo-bar-foobar* last");
        Query expectedQuery =
            new BooleanQuery.Builder()
                .add(new BooleanClause(new TermQuery(new Term(STRING_FIELD_NAME, "first")), defaultOp))
                .add(new BooleanQuery.Builder()
                    .add(new BooleanClause(new TermQuery(new Term(STRING_FIELD_NAME, "foo")), defaultOp))
                    .add(new BooleanClause(new TermQuery(new Term(STRING_FIELD_NAME, "bar")), defaultOp))
                    .add(new BooleanClause(new PrefixQuery(new Term(STRING_FIELD_NAME, "foobar")), defaultOp))
                    .build(), defaultOp)
                .add(new BooleanClause(new TermQuery(new Term(STRING_FIELD_NAME, "last")), defaultOp))
                .build();
        assertThat(query, Matchers.equalTo(expectedQuery));
    }
}
项目:elasticsearch_my    文件:QueryStringQueryBuilderTests.java   
public void testToQueryWilcardQueryWithSynonyms() throws Exception {
    assumeTrue("test runs only when at least a type is registered", getCurrentTypes().length > 0);
    for (Operator op : Operator.values()) {
        BooleanClause.Occur defaultOp = op.toBooleanClauseOccur();
        MapperQueryParser queryParser = new MapperQueryParser(createShardContext());
        QueryParserSettings settings = new QueryParserSettings("first foo-bar-foobar* last");
        settings.defaultField(STRING_FIELD_NAME);
        settings.fieldsAndWeights(Collections.emptyMap());
        settings.analyzeWildcard(true);
        settings.fuzziness(Fuzziness.AUTO);
        settings.rewriteMethod(MultiTermQuery.CONSTANT_SCORE_REWRITE);
        settings.defaultOperator(op.toQueryParserOperator());
        settings.forceAnalyzer(new MockRepeatAnalyzer());
        queryParser.reset(settings);
        Query query = queryParser.parse("first foo-bar-foobar* last");

        Query expectedQuery = new BooleanQuery.Builder()
            .add(new BooleanClause(new SynonymQuery(new Term(STRING_FIELD_NAME, "first"),
                new Term(STRING_FIELD_NAME, "first")), defaultOp))
            .add(new BooleanQuery.Builder()
                .add(new BooleanClause(new SynonymQuery(new Term(STRING_FIELD_NAME, "foo"),
                    new Term(STRING_FIELD_NAME, "foo")), defaultOp))
                .add(new BooleanClause(new SynonymQuery(new Term(STRING_FIELD_NAME, "bar"),
                    new Term(STRING_FIELD_NAME, "bar")), defaultOp))
                .add(new BooleanQuery.Builder()
                    .add(new BooleanClause(new PrefixQuery(new Term(STRING_FIELD_NAME, "foobar")),
                        BooleanClause.Occur.SHOULD))
                    .add(new BooleanClause(new PrefixQuery(new Term(STRING_FIELD_NAME, "foobar")),
                        BooleanClause.Occur.SHOULD))
                    .setDisableCoord(true)
                    .build(), defaultOp)
                .build(), defaultOp)
            .add(new BooleanClause(new SynonymQuery(new Term(STRING_FIELD_NAME, "last"),
                new Term(STRING_FIELD_NAME, "last")), defaultOp))
            .build();
        assertThat(query, Matchers.equalTo(expectedQuery));
    }
}
项目:elasticsearch_my    文件:DisMaxQueryBuilderTests.java   
public void testToQueryInnerPrefixQuery() throws Exception {
    assumeTrue("test runs only when at least a type is registered", getCurrentTypes().length > 0);
    String queryAsString = "{\n" +
            "    \"dis_max\":{\n" +
            "        \"queries\":[\n" +
            "            {\n" +
            "                \"prefix\":{\n" +
            "                    \"" + STRING_FIELD_NAME + "\":{\n" +
            "                        \"value\":\"sh\",\n" +
            "                        \"boost\":1.2\n" +
            "                    }\n" +
            "                }\n" +
            "            }\n" +
            "        ]\n" +
            "    }\n" +
            "}";
    Query query = parseQuery(queryAsString).toQuery(createShardContext());
    assertThat(query, instanceOf(DisjunctionMaxQuery.class));
    DisjunctionMaxQuery disjunctionMaxQuery = (DisjunctionMaxQuery) query;

    List<Query> disjuncts = disjunctionMaxQuery.getDisjuncts();
    assertThat(disjuncts.size(), equalTo(1));

    assertThat(disjuncts.get(0), instanceOf(BoostQuery.class));
    BoostQuery boostQuery = (BoostQuery) disjuncts.get(0);
    assertThat((double) boostQuery.getBoost(), closeTo(1.2, 0.00001));
    assertThat(boostQuery.getQuery(), instanceOf(PrefixQuery.class));
    PrefixQuery firstQ = (PrefixQuery) boostQuery.getQuery();
    // since age is automatically registered in data, we encode it as numeric
    assertThat(firstQ.getPrefix(), equalTo(new Term(STRING_FIELD_NAME, "sh")));

}
项目:lams    文件:PrefixWildcardQueryNodeBuilder.java   
@Override
public PrefixQuery build(QueryNode queryNode) throws QueryNodeException {    

  PrefixWildcardQueryNode wildcardNode = (PrefixWildcardQueryNode) queryNode;

  String text = wildcardNode.getText().subSequence(0, wildcardNode.getText().length() - 1).toString();
  PrefixQuery q = new PrefixQuery(new Term(wildcardNode.getFieldAsString(), text));

  MultiTermQuery.RewriteMethod method = (MultiTermQuery.RewriteMethod)queryNode.getTag(MultiTermRewriteMethodProcessor.TAG_ID);
  if (method != null) {
    q.setRewriteMethod(method);
  }

  return q;
}
项目:lams    文件:SimpleQueryParser.java   
/**
 * Factory method to generate a prefix query.
 */
protected Query newPrefixQuery(String text) {
  BooleanQuery bq = new BooleanQuery(true);
  for (Map.Entry<String,Float> entry : weights.entrySet()) {
    PrefixQuery prefix = new PrefixQuery(new Term(entry.getKey(), text));
    prefix.setBoost(entry.getValue());
    bq.add(prefix, BooleanClause.Occur.SHOULD);
  }
  return simplify(bq);
}
项目:para-search-elasticsearch    文件:ElasticSearchUtils.java   
private static QueryBuilder prefix(Query q) {
    QueryBuilder qb;
    String field = ((PrefixQuery) q).getPrefix().field();
    String value = ((PrefixQuery) q).getPrefix().text();
    if (StringUtils.isBlank(field)) {
        qb = multiMatchQuery(value);
    } else if (nestedMode() && field.matches(PROPS_REGEX)) {
        qb = nestedPropsQuery(keyValueBoolQuery(field, prefixQuery(getValueFieldName(value), value)));
    } else {
        qb = prefixQuery(field, value);
    }
    return qb;
}
项目:Elasticsearch    文件:TypeFieldMapper.java   
@Override
public Query termQuery(Object value, @Nullable QueryParseContext context) {
    if (indexOptions() == IndexOptions.NONE) {
        return new ConstantScoreQuery(new PrefixQuery(new Term(UidFieldMapper.NAME, Uid.typePrefixAsBytes(BytesRefs.toBytesRef(value)))));
    }
    return new ConstantScoreQuery(new TermQuery(createTerm(value)));
}
项目:rsterminology    文件:Search.java   
private static Query queryFromString(Analyzer analyzer, String searchText, int fuzzy) {
    if (searchText != null && !searchText.isEmpty()) {
        BooleanQuery.Builder b = new BooleanQuery.Builder();
        try (TokenStream stream = analyzer.tokenStream(FIELD_TERM, searchText)) {
            CharTermAttribute termAtt = stream.addAttribute(CharTermAttribute.class);
            stream.reset();
            while (stream.incrementToken()) {
                String s = termAtt.toString();
                Term term = new Term("term", s);
                Query tq = s.length() > MINIMUM_CHARS_FOR_FUZZY_SEARCH && fuzzy > 0 ? new FuzzyQuery(term, fuzzy) : new TermQuery(term);
                if (s.length() >= MINIMUM_CHARS_FOR_PREFIX_SEARCH) {
                    PrefixQuery pq = new PrefixQuery(new Term("term", s));
                    pq.setRewriteMethod(PrefixQuery.SCORING_BOOLEAN_REWRITE);
                    BooleanQuery bq = new BooleanQuery.Builder().add(tq, Occur.SHOULD).add(pq, Occur.SHOULD).build();
                    b.add(bq, Occur.MUST);
                }
                else {
                    b.add(tq,Occur.MUST);
                }
            }
            stream.end();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return b.build();
    }
    return null;
}
项目:NGB    文件:FeatureIndexDao.java   
/**
 * Searches genes by it's ID in project's gene files. Minimum featureId prefix length == 2
 *
 * @param featureId a feature ID prefix to search for
 * @param featureFiles a gene file ,from which to search
 * @return a {@code List} of {@code FeatureIndexEntry}
 * @throws IOException
 */
public IndexSearchResult<FeatureIndexEntry> searchFeatures(String featureId,
        List<? extends FeatureFile> featureFiles,
        Integer maxResultsCount)
        throws IOException {
    if (featureId == null || featureId.length() < 2) {
        return new IndexSearchResult<>(Collections.emptyList(), false, 0);
    }

    BooleanQuery.Builder mainBuilder = new BooleanQuery.Builder();

    PrefixQuery prefixQuery = new PrefixQuery(new Term(FeatureIndexFields.FEATURE_ID.getFieldName(),
            featureId.toLowerCase()));
    BooleanQuery.Builder prefixQueryBuilder = new BooleanQuery.Builder();
    prefixQueryBuilder.add(prefixQuery, BooleanClause.Occur.SHOULD);
    prefixQueryBuilder.add(new PrefixQuery(new Term(FeatureIndexFields.FEATURE_NAME.getFieldName(), featureId
            .toLowerCase())), BooleanClause.Occur.SHOULD);

    mainBuilder.add(prefixQueryBuilder.build(), BooleanClause.Occur.MUST);

    BooleanQuery.Builder featureTypeBuilder = new BooleanQuery.Builder();
    featureTypeBuilder.add(new TermQuery(new Term(FeatureIndexFields.FEATURE_TYPE.getFieldName(),
            FeatureType.GENE.getFileValue())), BooleanClause.Occur.SHOULD);
    featureTypeBuilder.add(new TermQuery(new Term(FeatureIndexFields.FEATURE_TYPE.getFieldName(),
            FeatureType.MRNA.getFileValue())), BooleanClause.Occur.SHOULD);
    featureTypeBuilder.add(new TermQuery(new Term(FeatureIndexFields.FEATURE_TYPE.getFieldName(),
            FeatureType.BOOKMARK.getFileValue())), BooleanClause.Occur.SHOULD);
    featureTypeBuilder.add(new TermQuery(new Term(FeatureIndexFields.FEATURE_TYPE.getFieldName(),
            FeatureType.BED_FEATURE.getFileValue())), BooleanClause.Occur.SHOULD);
    mainBuilder.add(featureTypeBuilder.build(), BooleanClause.Occur.MUST);

    return searchFileIndexes(featureFiles, mainBuilder.build(), null, maxResultsCount,
            new Sort(new SortField(FeatureIndexFields.FEATURE_NAME.getFieldName(), SortField.Type.STRING))
    );
}
项目:owsi-core-parent    文件:LuceneUtils.java   
@SuppressWarnings("unchecked")
public static String queryToString(Query luceneQuery) {
    StringBuilder sb = new StringBuilder();
    if (luceneQuery instanceof BooleanQuery) {
        sb.append(formatBooleanQuery((BooleanQuery) luceneQuery));
    } else if (luceneQuery instanceof TermQuery) {
        sb.append(formatTermQuery((TermQuery) luceneQuery));
    } else if (luceneQuery instanceof RawLuceneQuery) {
        sb.append(formatRawLuceneQuery((RawLuceneQuery) luceneQuery));
    } else if (luceneQuery instanceof FuzzyQuery) {
        sb.append(formatFuzzyQuery((FuzzyQuery) luceneQuery));
    } else if (luceneQuery instanceof PrefixQuery) {
        sb.append(formatPrefixQuery((PrefixQuery) luceneQuery));
    } else if (luceneQuery instanceof WildcardQuery) {
        sb.append(formatWildcardQuery((WildcardQuery) luceneQuery));
    } else if (luceneQuery instanceof NumericRangeQuery) {
        sb.append(formatNumericRangeQuery((NumericRangeQuery<? extends Number>) luceneQuery));
    } else if (luceneQuery instanceof IToQueryStringAwareLuceneQuery) {
        sb.append(((IToQueryStringAwareLuceneQuery) luceneQuery).toQueryString());
    } else if (luceneQuery instanceof BoostQuery) {
        sb.append(queryToString(((BoostQuery) luceneQuery).getQuery()));
        sb.append(BOOST_PARAMETER_PREFIX);
        sb.append(((BoostQuery) luceneQuery).getBoost());
    } else {
        throw new IllegalStateException(String.format("Query of type %1$s not supported",
                luceneQuery.getClass().getName()));
    }

    return sb.toString();
}
项目:owsi-core-parent    文件:LuceneUtils.java   
private static String formatPrefixQuery(PrefixQuery prefixQuery) {
    StringBuilder sb = new StringBuilder();
    Term prefix = prefixQuery.getPrefix();
    if (StringUtils.hasText(prefix.field())) {
        sb.append(prefix.field());
        sb.append(":");
    }
    sb.append(QueryParser.escape(prefix.text()));
    sb.append("*");
    return sb.toString();
}
项目:flea-db    文件:Query.java   
public static Query createPrefixQuery(final String field, final String value) {
    return new Query() {
        @Override
        public org.apache.lucene.search.Query getLuceneQuery(Schema schema) {
            validateType(field, schema, JsonNode.Type.STRING);
            return new PrefixQuery(new Term(field, value));
        }
    };
}
项目:search    文件:AnalyzingInfixSuggester.java   
/** This is called if the last token isn't ended
 *  (e.g. user did not type a space after it).  Return an
 *  appropriate Query clause to add to the BooleanQuery. */
protected Query getLastTokenQuery(String token) throws IOException {
  if (token.length() < minPrefixChars) {
    // The leading ngram was directly indexed:
    return new TermQuery(new Term("textgrams", token));
  }

  return new PrefixQuery(new Term(TEXT_FIELD_NAME, token));
}
项目:search    文件:PrefixWildcardQueryNodeBuilder.java   
@Override
public PrefixQuery build(QueryNode queryNode) throws QueryNodeException {    

  PrefixWildcardQueryNode wildcardNode = (PrefixWildcardQueryNode) queryNode;

  String text = wildcardNode.getText().subSequence(0, wildcardNode.getText().length() - 1).toString();
  PrefixQuery q = new PrefixQuery(new Term(wildcardNode.getFieldAsString(), text));

  MultiTermQuery.RewriteMethod method = (MultiTermQuery.RewriteMethod)queryNode.getTag(MultiTermRewriteMethodProcessor.TAG_ID);
  if (method != null) {
    q.setRewriteMethod(method);
  }

  return q;
}
项目:search    文件:SimpleQueryParser.java   
/**
 * Factory method to generate a prefix query.
 */
protected Query newPrefixQuery(String text) {
  BooleanQuery bq = new BooleanQuery(true);
  for (Map.Entry<String,Float> entry : weights.entrySet()) {
    PrefixQuery prefix = new PrefixQuery(new Term(entry.getKey(), text));
    prefix.setBoost(entry.getValue());
    bq.add(prefix, BooleanClause.Occur.SHOULD);
  }
  return simplify(bq);
}