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

项目:incubator-netbeans    文件:DocumentUtil.java   
static Query binaryNameQuery (final String resourceName) {
    final BooleanQuery query = new BooleanQuery ();
    int index = resourceName.lastIndexOf(BinaryName.PKG_SEPARATOR);  // NOI18N
    String pkgName, sName;
    if (index < 0) {
        pkgName = "";   // NOI18N
        sName = resourceName;
    }
    else {
        pkgName = resourceName.substring(0,index);
        sName = resourceName.substring(index+1);
    }
    sName = sName + WILDCARD_QUERY_WILDCARD;   //Type of type element (Enum, Class, Interface, Annotation)
    query.add (new TermQuery (new Term (FIELD_PACKAGE_NAME, pkgName)),BooleanClause.Occur.MUST);
    query.add (new WildcardQuery (new Term (FIELD_BINARY_NAME, sName)),BooleanClause.Occur.MUST);
    return query;
}
项目: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;
}
项目:Mastering-Java-EE-Development-with-WildFly    文件:SearchTestCase.java   
private List<Post> findPosts() {
    try {
        FullTextSession fullTextSession = getFullTextSession((Session) entityManager.getDelegate());
        Builder builder = new Builder();
        String[] fields = new String[] { "message.text", "topic.subject" };
        MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, new StandardAnalyzer());
        builder.add(parser.parse(POST_TEXT), MUST);
        builder.add(new TermQuery(new Term("topic.forum.id", "0")), MUST);
        builder.add(new TermQuery(new Term("topic.forum.category.id", "0")), MUST);
        builder.add(new WildcardQuery(new Term("poster.userId", "root")), MUST);
        addPostTimeQuery(builder);
        FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery(builder.build(), Post.class);
        fullTextQuery.setSort(getSort());
        fullTextQuery.setFirstResult(0);
        fullTextQuery.setMaxResults(15);
        @SuppressWarnings("unchecked")
        List<Post> posts = fullTextQuery.list();
        return posts;
    } catch (ParseException e) {
        logger.severe("error");
        return null;
    }
}
项目:elasticsearch_my    文件:QueryStringQueryBuilderTests.java   
public void testDisabledFieldNamesField() throws Exception {
    QueryShardContext context = createShardContext();
    context.getMapperService().merge("new_type",
        new CompressedXContent(
            PutMappingRequest.buildFromSimplifiedDef("new_type",
                "foo", "type=text",
                "_field_names", "enabled=false").string()),
        MapperService.MergeReason.MAPPING_UPDATE, true);
    QueryStringQueryBuilder queryBuilder = new QueryStringQueryBuilder("foo:*");
    Query query = queryBuilder.toQuery(context);
    Query expected = new WildcardQuery(new Term("foo", "*"));
    assertThat(query, equalTo(expected));
    context.getMapperService().merge("new_type",
        new CompressedXContent(
            PutMappingRequest.buildFromSimplifiedDef("new_type",
                "foo", "type=text",
                "_field_names", "enabled=true").string()),
        MapperService.MergeReason.MAPPING_UPDATE, true);
}
项目:oscm    文件:LuceneQueryBuilder.java   
private static BooleanQuery prepareWildcardQueryForSingleToken(String token,
        List<String> fieldNames, String locale, String defaultLocale,
        boolean isDefaultLocaleHandling) {

    BooleanQuery queryPart = new BooleanQuery();

    for (String fieldName : fieldNames) {
        if (isDefaultLocaleHandling) {
            if (locale.equals(defaultLocale)) {
                throw new IllegalArgumentException(
                        "For default locale handling, locale and default locale must be different");
            }
            BooleanQuery localeHandlingQuery = constructDefaultLocaleHandlingQuery(
                    fieldName, locale, defaultLocale, token);
            queryPart.add(localeHandlingQuery, Occur.SHOULD);
        } else {
            WildcardQuery wildcardQuery = new WildcardQuery(new Term(
                    fieldName + locale, "*" + token.toLowerCase() + "*"));
            queryPart.add(wildcardQuery, Occur.SHOULD);
        }

    }
    return queryPart;
}
项目:oscm    文件:LuceneQueryBuilder.java   
private static BooleanQuery constructDefaultLocaleHandlingQuery(
        String fieldName, String locale, String defaultLocale,
        String searchPhrase) {
    BooleanQuery bq1 = new BooleanQuery();
    TermQuery tq1 = new TermQuery(
            new Term(fieldName + ProductClassBridge.DEFINED_LOCALES_SUFFIX,
                    defaultLocale));
    TermQuery tq2 = new TermQuery(new Term(
            fieldName + ProductClassBridge.DEFINED_LOCALES_SUFFIX, locale));
    bq1.add(tq1, Occur.MUST);
    bq1.add(tq2, Occur.MUST_NOT);
    BooleanQuery bq2 = new BooleanQuery();
    WildcardQuery wq1 = new WildcardQuery(
            new Term(fieldName + defaultLocale,
                    "*" + searchPhrase.toLowerCase() + "*"));
    bq2.add(wq1, Occur.SHOULD);
    BooleanQuery finalQuery = new BooleanQuery();
    finalQuery.add(bq1, Occur.MUST);
    finalQuery.add(bq2, Occur.MUST);

    return finalQuery;
}
项目:gitplex-mit    文件:TextQuery.java   
@Override
protected void applyConstraints(BooleanQuery query) {
    if (fileNames != null) {
        BooleanQuery subQuery = new BooleanQuery(true);
        for (String pattern: Splitter.on(",").omitEmptyStrings().trimResults().split(fileNames.toLowerCase()))
            subQuery.add(new WildcardQuery(new Term(BLOB_NAME.name(), pattern)), Occur.SHOULD);
        if (subQuery.getClauses().length != 0)
            query.add(subQuery, Occur.MUST);
    }

    if (regex) 
        query.add(new RegexLiterals(term).asNGramQuery(BLOB_TEXT.name(), NGRAM_SIZE), Occur.MUST);
    else if (term.length() >= NGRAM_SIZE)
        query.add(new NGramLuceneQuery(BLOB_TEXT.name(), term, NGRAM_SIZE), Occur.MUST);
    else 
        throw new TooGeneralQueryException();
}
项目:gitplex-mit    文件:FileQuery.java   
@Override
protected void applyConstraints(BooleanQuery query) {
    boolean tooGeneral = true;
    for (char ch: fileNames.toCharArray()) {
        if (ch != '?' && ch != '*' && ch != ',' && ch != '.') {
            tooGeneral = false;
            break;
        }
    }
    if (tooGeneral)
        throw new TooGeneralQueryException();

    BooleanQuery subQuery = new BooleanQuery(true);
    for (String pattern: Splitter.on(",").omitEmptyStrings().trimResults().split(fileNames.toLowerCase()))
        subQuery.add(new WildcardQuery(new Term(BLOB_NAME.name(), pattern)), Occur.SHOULD);

    if (subQuery.getClauses().length != 0)
        query.add(subQuery, Occur.MUST);
    else
        throw new TooGeneralQueryException();
}
项目:linden    文件:TestLindenCore.java   
@Test
public void likeTest() throws Exception {
  String bql = "select * from linden by field1 like \"aa*\" source boost by 2";
  LindenSearchRequest request = bqlCompiler.compile(bql).getSearchRequest();
  Query query = QueryConstructor.constructQuery(request.getQuery(), lindenConfig);
  Assert.assertTrue(query instanceof WildcardQuery);
  Assert.assertEquals("field1:aa*^2.0", query.toString());
  LindenResult result = lindenCore.search(request);
  Assert.assertEquals(1, result.getTotalHits());

  bql = "select * from linden by field1 not like \"aaa*\" source";
  request = bqlCompiler.compile(bql).getSearchRequest();
  query = QueryConstructor.constructQuery(request.getQuery(), lindenConfig);
  Assert.assertTrue(query instanceof BooleanQuery);
  Assert.assertEquals("+*:* -field1:aaa*", query.toString());
  result = lindenCore.search(request);
  Assert.assertEquals(5, result.getTotalHits());
}
项目:rpmjukebox    文件:SearchManager.java   
private Query buildKeywordsQuery(String keywords, Query trackFilter) {
    Builder builder = new BooleanQuery.Builder();

    if ("*".equals(keywords)) {
        builder.add(new WildcardQuery(new Term(TrackField.KEYWORDS.name(), keywords)), BooleanClause.Occur.MUST);
    } else {
        // Split into whole words with the last word having
        // a wildcard '*' on the end
        for (StringTokenizer tokens = new StringTokenizer(keywords, " "); tokens.hasMoreTokens();) {
            String token = tokens.nextToken();

            if (tokens.hasMoreElements()) {
                builder.add(new TermQuery(new Term(TrackField.KEYWORDS.name(), token)), BooleanClause.Occur.MUST);
            } else {
                builder.add(new WildcardQuery(new Term(TrackField.KEYWORDS.name(), (token + "*"))),
                    BooleanClause.Occur.MUST);
            }
        }
    }

    if (trackFilter != null) {
        builder.add(trackFilter, BooleanClause.Occur.MUST);
    }

    return builder.build();
}
项目:intellij-ce-playground    文件:MavenClassSearcher.java   
protected Pair<String, Query> preparePatternAndQuery(String pattern) {
  pattern = pattern.toLowerCase();
  if (pattern.trim().length() == 0) {
    return new Pair<String, Query>(pattern, new MatchAllDocsQuery());
  }

  List<String> parts = StringUtil.split(pattern, ".");

  StringBuilder newPattern = new StringBuilder();
  for (int i = 0; i < parts.size() - 1; i++) {
    String each = parts.get(i);
    newPattern.append(each.trim());
    newPattern.append("*.");
  }

  String className = parts.get(parts.size() - 1);
  boolean exactSearch = className.endsWith(" ");
  newPattern.append(className.trim());
  if (!exactSearch) newPattern.append("*");

  pattern = newPattern.toString();
  String queryPattern = "*/" + pattern.replaceAll("\\.", "/");

  return new Pair<String, Query>(pattern, new WildcardQuery(new Term(TERM, queryPattern)));
}
项目:development    文件:LuceneQueryBuilder.java   
private static BooleanQuery prepareWildcardQueryForSingleToken(String token,
        List<String> fieldNames, String locale, String defaultLocale,
        boolean isDefaultLocaleHandling) {

    BooleanQuery queryPart = new BooleanQuery();

    for (String fieldName : fieldNames) {
        if (isDefaultLocaleHandling) {
            if (locale.equals(defaultLocale)) {
                throw new IllegalArgumentException(
                        "For default locale handling, locale and default locale must be different");
            }
            BooleanQuery localeHandlingQuery = constructDefaultLocaleHandlingQuery(
                    fieldName, locale, defaultLocale, token);
            queryPart.add(localeHandlingQuery, Occur.SHOULD);
        } else {
            WildcardQuery wildcardQuery = new WildcardQuery(new Term(
                    fieldName + locale, "*" + token.toLowerCase() + "*"));
            queryPart.add(wildcardQuery, Occur.SHOULD);
        }

    }
    return queryPart;
}
项目:development    文件:LuceneQueryBuilder.java   
private static BooleanQuery constructDefaultLocaleHandlingQuery(
        String fieldName, String locale, String defaultLocale,
        String searchPhrase) {
    BooleanQuery bq1 = new BooleanQuery();
    TermQuery tq1 = new TermQuery(
            new Term(fieldName + ProductClassBridge.DEFINED_LOCALES_SUFFIX,
                    defaultLocale));
    TermQuery tq2 = new TermQuery(new Term(
            fieldName + ProductClassBridge.DEFINED_LOCALES_SUFFIX, locale));
    bq1.add(tq1, Occur.MUST);
    bq1.add(tq2, Occur.MUST_NOT);
    BooleanQuery bq2 = new BooleanQuery();
    WildcardQuery wq1 = new WildcardQuery(
            new Term(fieldName + defaultLocale,
                    "*" + searchPhrase.toLowerCase() + "*"));
    bq2.add(wq1, Occur.SHOULD);
    BooleanQuery finalQuery = new BooleanQuery();
    finalQuery.add(bq1, Occur.MUST);
    finalQuery.add(bq2, Occur.MUST);

    return finalQuery;
}
项目:Krill    文件:TestWildcardIndex.java   
@Test
public void testWildcardStarWithCollection () throws IOException {
    ki = new KrillIndex();
    ki.addDoc(createFieldDoc1());
    ki.commit();
    // meine*
    WildcardQuery wcquery =
            new WildcardQuery(new Term("tokens", "s:meine*"));
    SpanMultiTermQueryWrapper<WildcardQuery> mtq =
            new SpanMultiTermQueryWrapper<WildcardQuery>(wcquery);

    // meine* /+w1:2,s0 &Erfahrung
    SpanQuery mdsq = new SpanMultipleDistanceQuery(
            new SpanClassQuery(mtq, (byte) 129),
            new SpanClassQuery(sq, (byte) 129), constraints, true, true);

    kr = ki.search(mdsq, (short) 10);
    assertEquals(4, kr.getMatches().size());
}
项目:Krill    文件:TestWildcardIndex.java   
@Test
public void testWildcardQuestionMark1 () throws IOException {
    ki = new KrillIndex();
    ki.addDoc(createFieldDoc1());
    ki.commit();

    // Wildcard ? means regex . (expects exactly one character)
    SpanMultiTermQueryWrapper<WildcardQuery> mtq =
            new SpanMultiTermQueryWrapper<WildcardQuery>(
                    new WildcardQuery(new Term("tokens", "s:meine?")));
    SpanMultipleDistanceQuery mdsq = new SpanMultipleDistanceQuery(
            new SpanClassQuery(mtq, (byte) 129),
            new SpanClassQuery(sq, (byte) 129), constraints, true, true);

    kr = ki.search(mdsq, (short) 10);
    assertEquals(3, kr.getMatches().size());

}
项目:Krill    文件:TestWildcardIndex.java   
@Test
public void testWildcardQuestionMark2 () throws IOException {
    ki = new KrillIndex();
    ki.addDoc(createFieldDoc1());
    ki.commit();

    // Wildcard ? means regex . (expects exactly one character)
    SpanMultiTermQueryWrapper<WildcardQuery> mtq =
            new SpanMultiTermQueryWrapper<WildcardQuery>(
                    new WildcardQuery(new Term("tokens", "s:mein?")));
    SpanMultipleDistanceQuery mdsq = new SpanMultipleDistanceQuery(
            new SpanClassQuery(mtq, (byte) 129),
            new SpanClassQuery(sq, (byte) 129), constraints, true, true);

    kr = ki.search(mdsq, (short) 10);
    assertEquals(1, kr.getMatches().size());

}
项目:universal-java-matrix-package    文件:LuceneMap.java   
@SuppressWarnings("unchecked")
public synchronized Set<K> keySet() {
    Set<K> set = new HashSet<K>();
    if (isEmpty()) {
        return set;
    }
    try {
        Term term = new Term(KEYSTRING, "*");
        WildcardQuery query = new WildcardQuery(term);
        TopDocs docs = getIndexSearcher().search(query, MAXSEARCHSIZE);

        for (ScoreDoc sd : docs.scoreDocs) {
            Document d = getIndexSearcher().doc(sd.doc);
            set.add((K) SerializationUtil.deserialize(d.getBinaryValue(KEYDATA).bytes));
        }
        return set;
    } catch (Exception e) {
        throw new RuntimeException("could not search documents", e);
    }
}
项目:peppol-directory    文件:PDQueryManager.java   
@Nullable
public static Query getContactLuceneQuery (@Nonnull @Nonempty final String sQueryString)
{
  ValueEnforcer.notEmpty (sQueryString, "QueryString");
  ValueEnforcer.notEmpty (sQueryString.trim (), "QueryString trimmed");

  if (sQueryString.length () < 3)
  {
    s_aLogger.warn ("Contact query string '" + sQueryString + "' is too short!");
    return null;
  }

  final Query aQuery1 = new WildcardQuery (PDField.CONTACT_TYPE.getContainsTerm (_lowerCase (sQueryString)));
  final Query aQuery2 = new WildcardQuery (PDField.CONTACT_NAME.getContainsTerm (_lowerCase (sQueryString)));
  final Query aQuery3 = new WildcardQuery (PDField.CONTACT_PHONE.getContainsTerm (_lowerCase (sQueryString)));
  final Query aQuery4 = new WildcardQuery (PDField.CONTACT_EMAIL.getContainsTerm (_lowerCase (sQueryString)));
  final Query aQuery = new BooleanQuery.Builder ().add (aQuery1, Occur.SHOULD)
                                                  .add (aQuery2, Occur.SHOULD)
                                                  .add (aQuery3, Occur.SHOULD)
                                                  .add (aQuery4, Occur.SHOULD)
                                                  .build ();
  return andNotDeleted (aQuery);
}
项目:java-data-mining-package    文件:LuceneIndex.java   
public Set<String> extractTerms(Query query) {
    Set<String> terms = new HashSet<String>();
    if (query instanceof BooleanQuery) {
        BooleanQuery b = (BooleanQuery) query;
        for (BooleanClause bc : b.getClauses()) {
            Query q = bc.getQuery();
            terms.addAll(extractTerms(q));
        }
    } else if (query instanceof TermQuery) {
        TermQuery tq = (TermQuery) query;
        terms.add(tq.getTerm().text());
    } else if (query instanceof WildcardQuery) {
        WildcardQuery wq = (WildcardQuery) query;
        terms.add(wq.getTerm().text());
    }
    return terms;
}
项目:search    文件:TestBlockJoinValidation.java   
@Test
public void testAdvanceValidationForToParentBjq() throws Exception {
  int randomChildNumber = getRandomChildNumber(0);
  // we need to make advance method meet wrong document, so random child number
  // in BJQ must be greater than child number in Boolean clause
  int nextRandomChildNumber = getRandomChildNumber(randomChildNumber);
  Query parentQueryWithRandomChild = createChildrenQueryWithOneParent(nextRandomChildNumber);
  ToParentBlockJoinQuery blockJoinQuery = new ToParentBlockJoinQuery(parentQueryWithRandomChild, parentsFilter, ScoreMode.None);
  // advance() method is used by ConjunctionScorer, so we need to create Boolean conjunction query
  BooleanQuery conjunctionQuery = new BooleanQuery();
  WildcardQuery childQuery = new WildcardQuery(new Term("child", createFieldValue(randomChildNumber)));
  conjunctionQuery.add(new BooleanClause(childQuery, BooleanClause.Occur.MUST));
  conjunctionQuery.add(new BooleanClause(blockJoinQuery, BooleanClause.Occur.MUST));

  thrown.expect(IllegalStateException.class);
  thrown.expectMessage("child query must only match non-parent docs");
  indexSearcher.search(conjunctionQuery, 1);
}
项目:search    文件:TestBlockJoinValidation.java   
@Test
public void testAdvanceValidationForToChildBjq() throws Exception {
  int randomChildNumber = getRandomChildNumber(0);
  // we need to make advance method meet wrong document, so random child number
  // in BJQ must be greater than child number in Boolean clause
  int nextRandomChildNumber = getRandomChildNumber(randomChildNumber);
  Query parentQueryWithRandomChild = createParentsQueryWithOneChild(nextRandomChildNumber);
  ToChildBlockJoinQuery blockJoinQuery = new ToChildBlockJoinQuery(parentQueryWithRandomChild, parentsFilter, false);
  // advance() method is used by ConjunctionScorer, so we need to create Boolean conjunction query
  BooleanQuery conjunctionQuery = new BooleanQuery();
  WildcardQuery childQuery = new WildcardQuery(new Term("child", createFieldValue(randomChildNumber)));
  conjunctionQuery.add(new BooleanClause(childQuery, BooleanClause.Occur.MUST));
  conjunctionQuery.add(new BooleanClause(blockJoinQuery, BooleanClause.Occur.MUST));

  thrown.expect(IllegalStateException.class);
  thrown.expectMessage(ToChildBlockJoinQuery.INVALID_QUERY_MESSAGE);
  indexSearcher.search(conjunctionQuery, 1);
}
项目:search    文件:KNearestNeighborClassifier.java   
/**
 * {@inheritDoc}
 */
@Override
public ClassificationResult<BytesRef> assignClass(String text) throws IOException {
  if (mlt == null) {
    throw new IOException("You must first call Classifier#train");
  }
  BooleanQuery mltQuery = new BooleanQuery();
  for (String textFieldName : textFieldNames) {
    mltQuery.add(new BooleanClause(mlt.like(textFieldName, new StringReader(text)), BooleanClause.Occur.SHOULD));
  }
  Query classFieldQuery = new WildcardQuery(new Term(classFieldName, "*"));
  mltQuery.add(new BooleanClause(classFieldQuery, BooleanClause.Occur.MUST));
  if (query != null) {
    mltQuery.add(query, BooleanClause.Occur.MUST);
  }
  TopDocs topDocs = indexSearcher.search(mltQuery, k);
  return selectClassFromNeighbors(topDocs);
}
项目: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);
}
项目:appformer    文件:LuceneSearchIndex.java   
private Query buildQuery(final Map<String, ?> attrs,
                         final ClusterSegment... clusterSegments) {
    final BooleanQuery.Builder query = new BooleanQuery.Builder();
    for (final Map.Entry<String, ?> entry : attrs.entrySet()) {
        if (entry.getValue() instanceof DateRange) {
            final Long from = ((DateRange) entry.getValue()).after().getTime();
            final Long to = ((DateRange) entry.getValue()).before().getTime();
            query.add(newLongRange(entry.getKey(),
                                   from,
                                   to,
                                   true,
                                   true),
                      MUST);
        } else if (entry.getValue() instanceof String) {
            query.add(new WildcardQuery(new Term(entry.getKey(),
                                                 entry.getValue().toString())),
                      MUST);
        } else if (entry.getValue() instanceof Boolean) {
            query.add(new TermQuery(new Term(entry.getKey(),
                                             ((Boolean) entry.getValue()) ? "0" : "1")),
                      MUST);
        }
    }
    return composeQuery(query.build(),
                        clusterSegments);
}
项目:appformer    文件:ElasticSearchSearchIndex.java   
private Query buildQuery(final Map<String, ?> attrs,
                         final ClusterSegment... clusterSegments) {
    final BooleanQuery.Builder query = new BooleanQuery.Builder();
    for (final Map.Entry<String, ?> entry : attrs.entrySet()) {
        if (entry.getValue() instanceof DateRange) {
            final Long from = ((DateRange) entry.getValue()).after().getTime();
            final Long to = ((DateRange) entry.getValue()).before().getTime();
            query.add(newLongRange(entry.getKey(),
                                   from,
                                   to,
                                   true,
                                   true),
                      MUST);
        } else if (entry.getValue() instanceof String) {
            query.add(new WildcardQuery(new Term(entry.getKey(),
                                                 entry.getValue().toString())),
                      MUST);
        } else if (entry.getValue() instanceof Boolean) {
            query.add(new TermQuery(new Term(entry.getKey(),
                                             ((Boolean) entry.getValue()) ? "0" : "1")),
                      MUST);
        }
    }
    return composeQuery(query.build(),
                        clusterSegments);
}
项目:OpenSPIFe    文件:PlanSearcher.java   
/**
 * Given a search input and a field name to search against, we can
 * create a query and add it to our vector of queries.
 * 
 * @param searchInput
 * @param fieldName
 */
public void addQuery(String fieldName, String searchInput){
    if(searchInput.equals("")){
        return;
    }

    searchInput = searchInput.toLowerCase();
    StringTokenizer tokenizer = new StringTokenizer(searchInput, PlanSearchConstants.DELIMITERS);   

    boolean first = true;
    while(tokenizer.hasMoreTokens()){
        String term = tokenizer.nextToken();
        if (first) {
            term = "*"+term;
            first = false;
        }
        if (!tokenizer.hasMoreTokens()) {
            term += "*";
        }
        Query query = new WildcardQuery(new Term(fieldName, specialQuoting(term))); 
        queries.add(query);
    }
}
项目:OpenSPIFe    文件:PlanSearcher.java   
/**
 * Given a search input and a field name to search against, we can
 * create a query and add it to our vector of queries.
 * Finds plan elements with words containing all these substrings.
 * @param literalValue Literal value, not Lucene syntax.  Parsed into words.
 * @param fieldName
 * @see PlanSearchConstants.DELIMITERS
 */
public void addQueryForWordsContaining(String fieldName, String literalValue) {
    if(literalValue.equals("")){
        return;
    }

    literalValue = literalValue.toLowerCase();
    StringTokenizer tokenizer = new StringTokenizer(literalValue, PlanSearchConstants.DELIMITERS);  

    while(tokenizer.hasMoreTokens()){
        String term = tokenizer.nextToken();
        term = "*" + PlanSearcher.specialQuoting(term) + "*";

        Query query = new WildcardQuery(new Term(fieldName, term)); 
        queries.add(query);
    }
}
项目:OpenSPIFe    文件:PlanSearcher.java   
public void addQuery(String fieldName, String searchInput, String prefix
        , String suffix){
    if(searchInput.equals("")){
        return;
    }

    searchInput = searchInput.toLowerCase();
    StringTokenizer tokenizer = new StringTokenizer(searchInput, PlanSearchConstants.DELIMITERS);   

    boolean first = true;
    while(tokenizer.hasMoreTokens()){
        String term = tokenizer.nextToken();
        if (first) {
            term = prefix+term;
            first = false;
        }
        if (!tokenizer.hasMoreTokens()) {
            term += suffix;
        }
        Query query = new WildcardQuery(new Term(fieldName, term)); 
        queries.add(query);
    }
}
项目:community-edition-old    文件:Solr4QueryParser.java   
private SpanQuery wrapWildcardTerms(org.apache.lucene.index.Term term)
{
    String termText = term.text();
    SpanQuery nextSpanQuery;
    if ((termText != null) && (termText.contains("*") || termText.contains("?")))
    {
        org.apache.lucene.search.WildcardQuery wildQuery = new org.apache.lucene.search.WildcardQuery(term);
        SpanMultiTermQueryWrapper wrapper = new SpanMultiTermQueryWrapper<>(wildQuery);
        wrapper.setRewriteMethod(new TopTermsSpanBooleanQueryRewrite(topTermSpanRewriteLimit));
        nextSpanQuery = wrapper;
    }
    else
    {
        nextSpanQuery = new SpanTermQuery(term);
    }
    return nextSpanQuery;
}
项目:community-edition-old    文件:Solr4QueryParser.java   
@Override
protected Query newWildcardQuery(Term t)
{
    if(t.text().equals("*"))
    {
        BooleanQuery bQuery = new BooleanQuery();
        bQuery.add(createTermQuery(FIELD_FIELDS, t.field()), Occur.SHOULD);
        bQuery.add(createTermQuery(FIELD_PROPERTIES, t.field()), Occur.SHOULD);
        return bQuery;
    }
    else if (t.text().contains("\\"))
    {
        String regexp = SearchLanguageConversion.convert(SearchLanguageConversion.DEF_LUCENE, SearchLanguageConversion.DEF_REGEX, t.text());
        return new RegexpQuery(new Term(t.field(), regexp));
    }
    else
    {
        org.apache.lucene.search.WildcardQuery query = new org.apache.lucene.search.WildcardQuery(t);
        query.setRewriteMethod(new MultiTermQuery.TopTermsScoringBooleanQueryRewrite(topTermSpanRewriteLimit));
        return query;
    }
}
项目:reviki    文件:LuceneSearcher.java   
public Set<SearchMatch> search(final String queryString, final boolean provideExtracts, final boolean singleWiki) throws IOException, QuerySyntaxException {
  if (_dir == null || queryString == null || queryString.trim().length() == 0) {
    return Collections.emptySet();
  }
  return doReadOperation(new ReadOperation<Set<SearchMatch>>() {
    public Set<SearchMatch> execute(final IndexReader reader, final Searcher searcher, final Analyzer analyzer) throws IOException, ParseException {
      LinkedHashSet<SearchMatch> results = new LinkedHashSet<SearchMatch>();
      // Prefer path, then title then content matches (match equality is on page name)
      for (String field : ALL_SEARCH_FIELDS) {
        if (field.equals(FIELD_PATH_LOWER)) {
          final Query query = new WildcardQuery(new Term(FIELD_PATH_LOWER, "*" + queryString.toLowerCase() + "*"));
          results.addAll(doQuery(reader, analyzer, searcher, field, provideExtracts, query));
        }
        else {
          results.addAll(query(reader, analyzer, searcher, field, queryString, provideExtracts));
        }
      }
      return orderResults(results);
    }
  }, !singleWiki);
}
项目:SciGraph    文件:VocabularyNeo4jImpl.java   
void addCommonConstraints(Builder indexQuery, Query query) {
  // BooleanQuery categoryQueries = new BooleanQuery();
  Builder categoryQueriesBuilder = new BooleanQuery.Builder();
  for (String category : query.getCategories()) {
    categoryQueriesBuilder.add(new TermQuery(new Term(Concept.CATEGORY, category)), Occur.SHOULD);
  }
  if (!query.getCategories().isEmpty()) {
    indexQuery.add(new BooleanClause(categoryQueriesBuilder.build(), Occur.MUST));
  }

  // BooleanQuery prefixQueries = new BooleanQuery();
  Builder prefixQueriesBuilder = new BooleanQuery.Builder();
  for (String curie : query.getPrefixes()) {
    String prefix = curieUtil.getExpansion(curie);
    prefixQueriesBuilder.add(new WildcardQuery(new Term(CommonProperties.IRI, prefix + "*")),
        Occur.SHOULD);
  }
  if (!query.getPrefixes().isEmpty()) {
    indexQuery.add(new BooleanClause(prefixQueriesBuilder.build(), Occur.MUST));
  }
}
项目:tool    文件:NamedElementIndexAccess.java   
@Override
protected Query parse(final Criteria criteria) {
    final String searchTerm = criteria.searchTerm.toLowerCase();
    final BooleanQuery query = new BooleanQuery();
    final String[] terms = split(searchTerm);
    if ((criteria.matchType & MatchType.FULL_NAMES_ONLY | criteria.matchType & MatchType.DEFINITIONS) == 0) {
        query.add(new BooleanClause(newWildcardQuery(FIELD_NAME, searchTerm), Occur.SHOULD));
        query.add(new BooleanClause(newCommentQuery(terms), Occur.SHOULD));
    } else {
        if ((criteria.matchType & MatchType.FULL_NAMES_ONLY) > 0) {
            query.add(new BooleanClause(newPhraseQuery(FIELD_NAME, terms), Occur.SHOULD));
        }
        if ((criteria.matchType & MatchType.DEFINITIONS) > 0) {
            query.add(new BooleanClause(newCommentQuery(terms), Occur.SHOULD));
        }
    }
    if ((criteria.matchType & MatchType.EXTERNALS) == 0) {
        query.add(new BooleanClause(new WildcardQuery(new Term(FIELD_RESOURCE, "NIEM-Reference-external-*")),
                Occur.MUST_NOT));
    }
    return query;
}
项目:tools-idea    文件:MavenClassSearcher.java   
protected Pair<String, Query> preparePatternAndQuery(String pattern) {
  pattern = pattern.toLowerCase();
  if (pattern.trim().length() == 0) {
    return new Pair<String, Query>(pattern, new MatchAllDocsQuery());
  }

  List<String> parts = StringUtil.split(pattern, ".");

  StringBuilder newPattern = new StringBuilder();
  for (int i = 0; i < parts.size() - 1; i++) {
    String each = parts.get(i);
    newPattern.append(each.trim());
    newPattern.append("*.");
  }

  String className = parts.get(parts.size() - 1);
  boolean exactSearch = className.endsWith(" ");
  newPattern.append(className.trim());
  if (!exactSearch) newPattern.append("*");

  pattern = newPattern.toString();
  String queryPattern = "*/" + pattern.replaceAll("\\.", "/");

  return new Pair<String, Query>(pattern, new WildcardQuery(new Term(TERM, queryPattern)));
}
项目:read-open-source-code    文件:KNearestNeighborClassifier.java   
/**
 * {@inheritDoc}
 */
@Override
public ClassificationResult<BytesRef> assignClass(String text) throws IOException {
  if (mlt == null) {
    throw new IOException("You must first call Classifier#train");
  }
  BooleanQuery mltQuery = new BooleanQuery();
  for (String textFieldName : textFieldNames) {
    mltQuery.add(new BooleanClause(mlt.like(new StringReader(text), textFieldName), BooleanClause.Occur.SHOULD));
  }
  Query classFieldQuery = new WildcardQuery(new Term(classFieldName, "*"));
  mltQuery.add(new BooleanClause(classFieldQuery, BooleanClause.Occur.MUST));
  if (query != null) {
    mltQuery.add(query, BooleanClause.Occur.MUST);
  }
  TopDocs topDocs = indexSearcher.search(mltQuery, k);
  return selectClassFromNeighbors(topDocs);
}
项目:read-open-source-code    文件:KNearestNeighborClassifier.java   
/**
 * {@inheritDoc}
 */
@Override
public ClassificationResult<BytesRef> assignClass(String text) throws IOException {
  if (mlt == null) {
    throw new IOException("You must first call Classifier#train");
  }
  BooleanQuery mltQuery = new BooleanQuery();
  for (String textFieldName : textFieldNames) {
    mltQuery.add(new BooleanClause(mlt.like(new StringReader(text), textFieldName), BooleanClause.Occur.SHOULD));
  }
  Query classFieldQuery = new WildcardQuery(new Term(classFieldName, "*"));
  mltQuery.add(new BooleanClause(classFieldQuery, BooleanClause.Occur.MUST));
  if (query != null) {
    mltQuery.add(query, BooleanClause.Occur.MUST);
  }
  TopDocs topDocs = indexSearcher.search(mltQuery, k);
  return selectClassFromNeighbors(topDocs);
}
项目:NIEM-Modeling-Tool    文件:NamedElementIndexAccess.java   
@Override
protected Query parse(final Criteria criteria) {
    final String searchTerm = criteria.searchTerm.toLowerCase();
    final BooleanQuery query = new BooleanQuery();
    final String[] terms = split(searchTerm);
    if ((criteria.matchType & MatchType.FULL_NAMES_ONLY | criteria.matchType & MatchType.DEFINITIONS) == 0) {
        query.add(new BooleanClause(newWildcardQuery(FIELD_NAME, searchTerm), Occur.SHOULD));
        query.add(new BooleanClause(newCommentQuery(terms), Occur.SHOULD));
    } else {
        if ((criteria.matchType & MatchType.FULL_NAMES_ONLY) > 0) {
            query.add(new BooleanClause(newPhraseQuery(FIELD_NAME, terms), Occur.SHOULD));
        }
        if ((criteria.matchType & MatchType.DEFINITIONS) > 0) {
            query.add(new BooleanClause(newCommentQuery(terms), Occur.SHOULD));
        }
    }
    if ((criteria.matchType & MatchType.EXTERNALS) == 0) {
        query.add(new BooleanClause(new WildcardQuery(new Term(FIELD_RESOURCE, "NIEM-Reference-external-*")),
                Occur.MUST_NOT));
    }
    return query;
}
项目:kie-wb-common    文件:IndexFullTextTest.java   
@Test
public void testIndexingFullText() throws IOException, InterruptedException {
    //Add test files
    loadProperties("file1.properties",
                   basePath);
    loadProperties("file2.properties",
                   basePath);

    Thread.sleep(5000); //wait for events to be consumed from jgit -> (notify changes -> watcher -> index) -> lucene index

    List<String> index = Arrays.asList(KObjectUtil.toKCluster(basePath.getFileSystem()).getClusterId());

    searchFor(index,
              new WildcardQuery(new Term(FULL_TEXT_FIELD, "*file*")),
              2);
}
项目:Maskana-Gestor-de-Conocimiento    文件:KNearestNeighborClassifier.java   
/**
 * {@inheritDoc}
 */
@Override
public ClassificationResult<BytesRef> assignClass(String text) throws IOException {
  if (mlt == null) {
    throw new IOException("You must first call Classifier#train");
  }
  BooleanQuery mltQuery = new BooleanQuery();
  for (String textFieldName : textFieldNames) {
    mltQuery.add(new BooleanClause(mlt.like(new StringReader(text), textFieldName), BooleanClause.Occur.SHOULD));
  }
  Query classFieldQuery = new WildcardQuery(new Term(classFieldName, "*"));
  mltQuery.add(new BooleanClause(classFieldQuery, BooleanClause.Occur.MUST));
  if (query != null) {
    mltQuery.add(query, BooleanClause.Occur.MUST);
  }
  TopDocs topDocs = indexSearcher.search(mltQuery, k);
  return selectClassFromNeighbors(topDocs);
}
项目:t4f-data    文件:ScoreTest.java   
public void testWildcard() throws Exception {
  indexSingleFieldDocs(new Field[]
    { new Field("contents", "wild", Field.Store.YES, Field.Index.ANALYZED),
      new Field("contents", "child", Field.Store.YES, Field.Index.ANALYZED),
      new Field("contents", "mild", Field.Store.YES, Field.Index.ANALYZED),
      new Field("contents", "mildew", Field.Store.YES, Field.Index.ANALYZED) });

  IndexSearcher searcher = new IndexSearcher(directory);
  Query query = new WildcardQuery(new Term("contents", "?ild*"));  //#A
  TopDocs matches = searcher.search(query, 10);
  assertEquals("child no match", 3, matches.totalHits);

  assertEquals("score the same", matches.scoreDocs[0].score,
                                 matches.scoreDocs[1].score, 0.0);
  assertEquals("score the same", matches.scoreDocs[1].score,
                                 matches.scoreDocs[2].score, 0.0);
  searcher.close();
}