Example usage for org.apache.lucene.search PrefixQuery PrefixQuery

List of usage examples for org.apache.lucene.search PrefixQuery PrefixQuery

Introduction

In this page you can find the example usage for org.apache.lucene.search PrefixQuery PrefixQuery.

Prototype

public PrefixQuery(Term prefix) 

Source Link

Document

Constructs a query for terms starting with prefix.

Usage

From source file:SearcherTest.java

/**
 * PrefixQuery  PrefixQuery?xxx%//from   www .  j av a 2 s  .  c  o  m
 *
 * @throws Exception
 */
@Test
public void testPrefixQuery() throws Exception {
    String searchField = "contents";
    String q = "1license";
    Term t = new Term(searchField, q);
    Query query = new PrefixQuery(t);
    TopDocs hits = is.search(query, 10);
    System.out.println("? '" + q + "'" + hits.totalHits + "");

    for (ScoreDoc scoreDoc : hits.scoreDocs) {
        Document doc = is.doc(scoreDoc.doc);
        System.out.println(doc.get("fullPath"));
    }
}

From source file:aos.lucene.search.msc.PrefixQueryTest.java

License:Apache License

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();/* www .j a  va  2s  .co  m*/
    dir.close();
}

From source file:br.bireme.ngrams.NGrams.java

public static void deleteDocument(final String id, final NGIndex index) throws IOException {
    if (id == null) {
        throw new NullPointerException("id");
    }/*from  w w w  .j ava  2  s  .  c o m*/
    if (index == null) {
        throw new NullPointerException("index");
    }
    final String idN = Tools.limitSize(Tools.normalize(id, OCC_SEPARATOR), MAX_NG_TEXT_SIZE).trim();

    try (IndexWriter writer = index.getIndexWriter(true)) {
        final Query query;
        if (id.trim().endsWith("*")) { // delete all documents with same prefix
            query = new PrefixQuery(new Term("id", idN.substring(0, idN.length() - 1)));
        } else {
            query = new TermQuery(new Term("id", idN));
        }

        writer.deleteDocuments(query);
        writer.commit();
    }
}

From source file:br.ufmt.harmonizacao.implementer.PatenteeSearcher.java

public List<String> search(String field, String value) {
    try {//from ww w .j  a  v a 2 s.  co m
        long start = System.currentTimeMillis();
        TokenStream stream = analyzer.tokenStream(field, new StringReader(value));
        CharTermAttribute attr = stream.getAttribute(CharTermAttribute.class);
        stream.reset();
        String valor = "";
        while (stream.incrementToken()) {
            valor = valor + attr.toString() + ' ';
        }
        BooleanQuery bq = new BooleanQuery();
        BooleanQuery acronymBq = null;
        String query = "";
        BooleanQuery wrapBq = new BooleanQuery();
        String[] tokens = valor.split(" ");
        for (int i = 0; i < tokens.length; i++) {
            if (tokens.length >= 2) {
                acronymBq = new BooleanQuery();
                switch (i) {
                case 0:
                    acronymBq.add(new PrefixQuery(new Term(field, tokens[i])), BooleanClause.Occur.MUST);
                    bq.add(new PrefixQuery(new Term(field, tokens[i])), BooleanClause.Occur.SHOULD);
                    break;
                case 1:
                    acronymBq.add(new FuzzyQuery(new Term(field, tokens[i])), BooleanClause.Occur.MUST_NOT);
                    bq.add(new FuzzyQuery(new Term(field, tokens[i])), BooleanClause.Occur.SHOULD);
                    bq.add(new LengthQuery(field, valor), BooleanClause.Occur.MUST_NOT);
                    break;
                default:
                    break;
                }
            } else {
                if (tokens[i].length() > 3) {
                    bq.add(new FuzzyQuery(new Term(field, tokens[i])), BooleanClause.Occur.MUST);
                } else {
                    bq.add(new TermQuery(new Term(field, tokens[i])), BooleanClause.Occur.MUST);
                }
            }
        }

        stream.end();
        stream.close();
        // Aqui termina
        // Cria uma fuzzyquery, ela que far a busca de aproximao

        wrapBq.add(bq, BooleanClause.Occur.MUST);
        if (acronymBq != null) {
            //new QueryParser(Version.LUCENE_47, field, new StandardAnalyzer(Version.LUCENE_47)).parse(query)
            wrapBq.add(acronymBq, BooleanClause.Occur.MUST_NOT);
        }
        String queryTime = "Tempo para construo da query : " + (System.currentTimeMillis() - start) + "ms";
        // Pegando os documentos encontrado na pesquisa
        start = System.currentTimeMillis();
        ScoreDoc[] hits = searcher.search(wrapBq, 10).scoreDocs;
        String searchTime = "Tempo para busca : " + (System.currentTimeMillis() - start) + "ms";
        List<String> result = new ArrayList<String>();
        result.add(valor);
        if (hits.length > 0) {
            for (int i = 0; i < hits.length; i++) {
                Document hitDoc = searcher.doc(hits[i].doc);
                result.add(hitDoc.get(field));
            }
        }
        result.add(queryTime);
        result.add(searchTime);
        return result;
    } catch (IOException ex) {
        Logger.getLogger(PatenteeSearcher.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:brightsolid.solr.plugins.TestTargetPositionQueryFuzzy.java

License:Apache License

public void testTargetPositionPrefix() throws Exception {
    PrefixQuery fq = new PrefixQuery(new Term("field", "tw"));
    SpanQuery stq = new SpanMultiTermQueryWrapper<PrefixQuery>(fq);
    SpanQuery tpq = new SpanTargetPositionQuery(stq, 2);
    TopDocs td = searcher.search(tpq, 10);

    assertEquals(fieldValue(td, 0), "threx one twp");
    assertEquals(3, td.totalHits);/*from   w w w.ja v a  2 s .c  o  m*/
}

From source file:com.amalto.core.storage.hibernate.LuceneQueryGenerator.java

License:Open Source License

@Override
public Query visit(final FullText fullText) {
    // TODO Test me on conditions where many types share same field names.
    final Map<String, Boolean> fieldsMap = new HashMap<String, Boolean>();
    for (final ComplexTypeMetadata type : types) {
        type.accept(new DefaultMetadataVisitor<Void>() {

            @Override//  ww w. j  ava  2  s.  c o  m
            public Void visit(ContainedComplexTypeMetadata containedType) {
                super.visit(containedType);
                for (ComplexTypeMetadata subType : containedType.getSubTypes()) {
                    subType.accept(this);
                }
                return null;
            }

            @Override
            public Void visit(ReferenceFieldMetadata referenceField) {
                ComplexTypeMetadata referencedType = referenceField.getReferencedType();
                if (!referencedType.isInstantiable()) {
                    referencedType.accept(this);
                }
                return null;
            }

            @Override
            public Void visit(SimpleTypeFieldMetadata simpleField) {
                if (!Storage.METADATA_TIMESTAMP.equals(simpleField.getName())
                        && !Storage.METADATA_TASK_ID.equals(simpleField.getName())) {
                    if (StorageMetadataUtils.isValueSearchable(fullText.getValue(), simpleField)) {
                        fieldsMap.put(simpleField.getName(), simpleField.isKey());
                    }
                }
                return null;
            }

            @Override
            public Void visit(EnumerationFieldMetadata enumField) {
                if (StorageMetadataUtils.isValueAssignable(fullText.getValue(), enumField)) {
                    fieldsMap.put(enumField.getName(), enumField.isKey());
                }
                return null;
            }
        });
    }

    String[] fieldsAsArray = fieldsMap.keySet().toArray(new String[fieldsMap.size()]);
    StringBuilder queryBuffer = new StringBuilder();
    Iterator<Map.Entry<String, Boolean>> fieldsIterator = fieldsMap.entrySet().iterator();
    String fullTextValue = getFullTextValue(fullText);
    BooleanQuery query = new BooleanQuery();
    Query idQuery = null;
    while (fieldsIterator.hasNext()) {
        Map.Entry<String, Boolean> next = fieldsIterator.next();
        if (next.getValue()) {
            queryBuffer.append(next.getKey()).append(ToLowerCaseFieldBridge.ID_POSTFIX + ':')
                    .append(fullTextValue);
            idQuery = new PrefixQuery(new Term(next.getKey(), fullText.getValue()));
        } else {
            queryBuffer.append(next.getKey()).append(':').append(fullTextValue);
        }
        if (fieldsIterator.hasNext()) {
            queryBuffer.append(" OR "); //$NON-NLS-1$
        }
    }

    String fullTextQuery = queryBuffer.toString();
    if (idQuery != null) {
        query.add(idQuery, BooleanClause.Occur.SHOULD);
    }
    query.add(parseQuery(fieldsAsArray, fullTextQuery, fullText.getValue()), BooleanClause.Occur.SHOULD);
    return query;
}

From source file:com.amalto.core.storage.hibernate.LuceneQueryGenerator.java

License:Open Source License

@Override
public Query visit(FieldFullText fieldFullText) {
    String fieldName = fieldFullText.getField().getFieldMetadata().getName();
    String[] fieldsAsArray = new String[] { fieldName };
    String fullTextValue = getFullTextValue(fieldFullText);
    String fullTextQuery = fieldName + ':' + fullTextValue;
    if (fieldFullText.getField().getFieldMetadata().isKey()) {
        BooleanQuery query = new BooleanQuery();
        query.add(new PrefixQuery(new Term(fieldName, fieldFullText.getValue())), BooleanClause.Occur.SHOULD);
        fieldsAsArray = new String[] { fieldName + ToLowerCaseFieldBridge.ID_POSTFIX };
        fullTextQuery = fieldName + ToLowerCaseFieldBridge.ID_POSTFIX + ":" + fullTextValue; //$NON-NLS-1$
        query.add(parseQuery(fieldsAsArray, fullTextQuery, fieldFullText.getValue()),
                BooleanClause.Occur.SHOULD);
        return query;
    }//w  ww. j a va 2 s .com
    return parseQuery(fieldsAsArray, fullTextQuery, fieldFullText.getValue());
}

From source file:com.barchart.feed.ddf.resolver.provider.CodecHelper.java

License:BSD License

static Query buildQuerySimple(final String source) {

    final String[] termArray = source.split("\\s+");

    final BooleanQuery query = new BooleanQuery();

    for (final String termText : termArray) {

        final Term term = getBodyTerm(termText);

        if (hasWildcard(termText)) {
            AND(query, new WildcardQuery(term));
        } else {/*from www  .  ja v  a  2  s  .  com*/
            AND(query, new PrefixQuery(term));
        }

    }

    return query;

}

From source file:com.bewsia.script.safe.lucene.SEntity.java

License:Open Source License

public PrefixQuery newPrefixQuery(Term term) {
    return new PrefixQuery(term);
}

From source file:com.bluedragon.search.search.QueryAttributes.java

License:Open Source License

public boolean setCategoryTree(String categoryTree) {
    if (categoryTree == null || categoryTree.length() == 0)
        return false;

    Query catTreeQuery = new PrefixQuery(new Term(DocumentWrap.CATEGORYTREE, categoryTree));
    this.query = combineQueries(this.query, catTreeQuery);
    return true;/*from w w w . j a v  a 2 s  .  c  om*/
}