Search in sources :

Example 96 with WildcardQuery

use of org.apache.lucene.search.WildcardQuery in project querydsl by querydsl.

the class LuceneSerializer method startsWith.

protected Query startsWith(QueryMetadata metadata, Operation<?> operation, boolean ignoreCase) {
    verifyArguments(operation);
    Path<?> path = getPath(operation.getArg(0));
    String field = toField(path);
    String[] terms = convertEscaped(path, operation.getArg(1), metadata);
    if (terms.length > 1) {
        BooleanQuery bq = new BooleanQuery();
        for (int i = 0; i < terms.length; ++i) {
            String s = i == 0 ? terms[i] + "*" : "*" + terms[i] + "*";
            bq.add(new WildcardQuery(new Term(field, s)), Occur.MUST);
        }
        return bq;
    }
    return new PrefixQuery(new Term(field, terms[0]));
}
Also used : BooleanQuery(org.apache.lucene.search.BooleanQuery) WildcardQuery(org.apache.lucene.search.WildcardQuery) PrefixQuery(org.apache.lucene.search.PrefixQuery) Term(org.apache.lucene.index.Term)

Example 97 with WildcardQuery

use of org.apache.lucene.search.WildcardQuery in project neo4j by neo4j.

the class LuceneDocumentStructureTest method shouldBuildWildcardQueries.

@Test
void shouldBuildWildcardQueries() {
    // given
    WildcardQuery query = (WildcardQuery) LuceneDocumentStructure.newWildCardStringQuery("foo");
    // then
    assertEquals("string", query.getField());
}
Also used : WildcardQuery(org.apache.lucene.search.WildcardQuery) Test(org.junit.jupiter.api.Test)

Example 98 with WildcardQuery

use of org.apache.lucene.search.WildcardQuery in project graphdb by neo4j-attic.

the class ImdbExampleTest method doQueriesForNodes.

@Test
public void doQueriesForNodes() {
    IndexManager index = graphDb.index();
    Index<Node> actors = index.forNodes("actors");
    Index<Node> movies = index.forNodes("movies");
    Set<String> found = new HashSet<String>();
    @SuppressWarnings("serial") Set<String> expectedActors = new HashSet<String>() {

        {
            add("Monica Bellucci");
            add("Keanu Reeves");
        }
    };
    @SuppressWarnings("serial") Set<String> expectedMovies = new HashSet<String>() {

        {
            add("The Matrix");
        }
    };
    // START SNIPPET: actorsQuery
    for (Node actor : actors.query("name", "*e*")) {
        // This will return Reeves and Bellucci
        // END SNIPPET: actorsQuery
        found.add((String) actor.getProperty("name"));
    // START SNIPPET: actorsQuery
    }
    // END SNIPPET: actorsQuery
    assertEquals(expectedActors, found);
    found.clear();
    // START SNIPPET: matrixQuery
    for (Node movie : movies.query("title:*Matrix* AND year:1999")) {
        // This will return "The Matrix" from 1999 only.
        // END SNIPPET: matrixQuery
        found.add((String) movie.getProperty("title"));
    // START SNIPPET: matrixQuery
    }
    // END SNIPPET: matrixQuery
    assertEquals(expectedMovies, found);
    // START SNIPPET: matrixSingleQuery
    Node matrix = movies.query("title:*Matrix* AND year:2003").getSingle();
    // END SNIPPET: matrixSingleQuery
    assertEquals("The Matrix Reloaded", matrix.getProperty("title"));
    // START SNIPPET: queryWithScore
    IndexHits<Node> hits = movies.query("title", "The*");
    for (Node movie : hits) {
        System.out.println(movie.getProperty("title") + " " + hits.currentScore());
        // END SNIPPET: queryWithScore
        assertTrue(((String) movie.getProperty("title")).startsWith("The"));
    // START SNIPPET: queryWithScore
    }
    // END SNIPPET: queryWithScore
    assertEquals(2, hits.size());
    // START SNIPPET: queryWithRelevance
    hits = movies.query("title", new QueryContext("The*").sortByScore());
    // END SNIPPET: queryWithRelevance
    float previous = Float.MAX_VALUE;
    // START SNIPPET: queryWithRelevance
    for (Node movie : hits) {
        // hits sorted by relevance (score)
        // END SNIPPET: queryWithRelevance
        assertTrue(hits.currentScore() <= previous);
        previous = hits.currentScore();
    // START SNIPPET: queryWithRelevance
    }
    // END SNIPPET: queryWithRelevance
    assertEquals(2, hits.size());
    // START SNIPPET: termQuery
    // a TermQuery will give exact matches
    Node actor = actors.query(new TermQuery(new Term("name", "Keanu Reeves"))).getSingle();
    // END SNIPPET: termQuery
    assertEquals("Keanu Reeves", actor.getProperty("name"));
    Node theMatrix = movies.get("title", "The Matrix").getSingle();
    Node theMatrixReloaded = movies.get("title", "The Matrix Reloaded").getSingle();
    // START SNIPPET: wildcardTermQuery
    hits = movies.query(new WildcardQuery(new Term("title", "The Matrix*")));
    for (Node movie : hits) {
        System.out.println(movie.getProperty("title"));
        // END SNIPPET: wildcardTermQuery
        assertTrue(((String) movie.getProperty("title")).startsWith("The Matrix"));
    // START SNIPPET: wildcardTermQuery
    }
    // END SNIPPET: wildcardTermQuery
    assertEquals(2, hits.size());
    // START SNIPPET: numericRange
    movies.add(theMatrix, "year-numeric", new ValueContext(1999L).indexNumeric());
    movies.add(theMatrixReloaded, "year-numeric", new ValueContext(2003L).indexNumeric());
    // Query for range
    long startYear = 1997;
    long endYear = 2001;
    hits = movies.query(NumericRangeQuery.newLongRange("year-numeric", startYear, endYear, true, true));
    // END SNIPPET: numericRange
    assertEquals(theMatrix, hits.getSingle());
    // START SNIPPET: compoundQueries
    hits = movies.query("title:*Matrix* AND year:1999");
    // END SNIPPET: compoundQueries
    assertEquals(theMatrix, hits.getSingle());
    // START SNIPPET: defaultOperator
    QueryContext query = new QueryContext("title:*Matrix* year:1999").defaultOperator(Operator.AND);
    hits = movies.query(query);
    // END SNIPPET: defaultOperator
    // with OR the result would be 2 hits
    assertEquals(1, hits.size());
    // START SNIPPET: sortedResult
    hits = movies.query("title", new QueryContext("*").sort("title"));
    for (Node hit : hits) {
    // all movies with a title in the index, ordered by title
    }
    // END SNIPPET: sortedResult
    assertEquals(3, hits.size());
    // START SNIPPET: sortedResult
    // or
    hits = movies.query(new QueryContext("title:*").sort("year", "title"));
    for (Node hit : hits) {
    // all movies with a title in the index, ordered by year, then title
    }
    // END SNIPPET: sortedResult
    assertEquals(3, hits.size());
}
Also used : ValueContext(org.neo4j.index.lucene.ValueContext) TermQuery(org.apache.lucene.search.TermQuery) WildcardQuery(org.apache.lucene.search.WildcardQuery) Node(org.neo4j.graphdb.Node) QueryContext(org.neo4j.index.lucene.QueryContext) Term(org.apache.lucene.index.Term) IndexManager(org.neo4j.graphdb.index.IndexManager) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 99 with WildcardQuery

use of org.apache.lucene.search.WildcardQuery in project neo4j by neo4j.

the class FulltextIndexReader method query.

@Override
public void query(QueryContext context, IndexProgressor.EntityValueClient client, IndexQueryConstraints constraints, PropertyIndexQuery... queries) throws IndexNotApplicableKernelException {
    BooleanQuery.Builder queryBuilder = new BooleanQuery.Builder();
    for (PropertyIndexQuery indexQuery : queries) {
        if (indexQuery.type() == PropertyIndexQuery.IndexQueryType.fulltextSearch) {
            PropertyIndexQuery.FulltextSearchPredicate fulltextSearch = (PropertyIndexQuery.FulltextSearchPredicate) indexQuery;
            try {
                queryBuilder.add(parseFulltextQuery(fulltextSearch.query()), BooleanClause.Occur.SHOULD);
            } catch (ParseException e) {
                throw new RuntimeException("Could not parse the given fulltext search query: '" + fulltextSearch.query() + "'.", e);
            }
        } else {
            // Not fulltext query
            assertNotComposite(queries);
            assertCypherCompatible();
            Query query;
            if (indexQuery.type() == PropertyIndexQuery.IndexQueryType.stringContains) {
                PropertyIndexQuery.StringContainsPredicate scp = (PropertyIndexQuery.StringContainsPredicate) indexQuery;
                String searchTerm = QueryParser.escape(scp.contains().stringValue());
                Term term = new Term(propertyNames[0], "*" + searchTerm + "*");
                query = new WildcardQuery(term);
            } else if (indexQuery.type() == PropertyIndexQuery.IndexQueryType.stringSuffix) {
                PropertyIndexQuery.StringSuffixPredicate ssp = (PropertyIndexQuery.StringSuffixPredicate) indexQuery;
                String searchTerm = QueryParser.escape(ssp.suffix().stringValue());
                Term term = new Term(propertyNames[0], "*" + searchTerm);
                query = new WildcardQuery(term);
            } else if (indexQuery.type() == PropertyIndexQuery.IndexQueryType.stringPrefix) {
                PropertyIndexQuery.StringPrefixPredicate spp = (PropertyIndexQuery.StringPrefixPredicate) indexQuery;
                String searchTerm = spp.prefix().stringValue();
                Term term = new Term(propertyNames[0], searchTerm);
                query = new LuceneDocumentStructure.PrefixMultiTermsQuery(term);
            } else if (indexQuery.getClass() == PropertyIndexQuery.ExactPredicate.class && indexQuery.valueGroup() == ValueGroup.TEXT) {
                PropertyIndexQuery.ExactPredicate exact = (PropertyIndexQuery.ExactPredicate) indexQuery;
                String searchTerm = ((TextValue) exact.value()).stringValue();
                Term term = new Term(propertyNames[0], searchTerm);
                query = new ConstantScoreQuery(new TermQuery(term));
            } else if (indexQuery.getClass() == PropertyIndexQuery.TextRangePredicate.class) {
                PropertyIndexQuery.TextRangePredicate sp = (PropertyIndexQuery.TextRangePredicate) indexQuery;
                query = newRangeSeekByStringQuery(propertyNames[0], sp.from(), sp.fromInclusive(), sp.to(), sp.toInclusive());
            } else {
                throw new IndexNotApplicableKernelException("A fulltext schema index cannot answer " + indexQuery.type() + " queries on " + indexQuery.valueCategory() + " values.");
            }
            queryBuilder.add(query, BooleanClause.Occur.MUST);
        }
    }
    Query query = queryBuilder.build();
    ValuesIterator itr = searchLucene(query, constraints, context, context.cursorContext(), context.memoryTracker());
    IndexProgressor progressor = new FulltextIndexProgressor(itr, client, constraints);
    client.initialize(index, progressor, queries, constraints, true);
}
Also used : BooleanQuery(org.apache.lucene.search.BooleanQuery) WildcardQuery(org.apache.lucene.search.WildcardQuery) Query(org.apache.lucene.search.Query) ConstantScoreQuery(org.apache.lucene.search.ConstantScoreQuery) WildcardQuery(org.apache.lucene.search.WildcardQuery) TermQuery(org.apache.lucene.search.TermQuery) BooleanQuery(org.apache.lucene.search.BooleanQuery) TermRangeQuery(org.apache.lucene.search.TermRangeQuery) PropertyIndexQuery(org.neo4j.internal.kernel.api.PropertyIndexQuery) PropertyIndexQuery(org.neo4j.internal.kernel.api.PropertyIndexQuery) ConstantScoreQuery(org.apache.lucene.search.ConstantScoreQuery) LuceneDocumentStructure(org.neo4j.kernel.api.impl.schema.LuceneDocumentStructure) TermQuery(org.apache.lucene.search.TermQuery) Term(org.apache.lucene.index.Term) IndexNotApplicableKernelException(org.neo4j.internal.kernel.api.exceptions.schema.IndexNotApplicableKernelException) IndexProgressor(org.neo4j.kernel.api.index.IndexProgressor) ParseException(org.apache.lucene.queryparser.classic.ParseException) ValuesIterator(org.neo4j.kernel.api.impl.index.collector.ValuesIterator)

Example 100 with WildcardQuery

use of org.apache.lucene.search.WildcardQuery in project neo4j by neo4j.

the class LuceneDocumentStructure method newWildCardStringQuery.

public static Query newWildCardStringQuery(String searchFor) {
    String searchTerm = QueryParser.escape(searchFor);
    Term term = new Term(ValueEncoding.String.key(0), "*" + searchTerm + "*");
    return new WildcardQuery(term);
}
Also used : WildcardQuery(org.apache.lucene.search.WildcardQuery) Term(org.apache.lucene.index.Term)

Aggregations

WildcardQuery (org.apache.lucene.search.WildcardQuery)102 Term (org.apache.lucene.index.Term)94 BooleanQuery (org.apache.lucene.search.BooleanQuery)38 TermQuery (org.apache.lucene.search.TermQuery)38 Query (org.apache.lucene.search.Query)29 PrefixQuery (org.apache.lucene.search.PrefixQuery)27 FuzzyQuery (org.apache.lucene.search.FuzzyQuery)23 Document (org.apache.lucene.document.Document)19 IndexSearcher (org.apache.lucene.search.IndexSearcher)17 RegexpQuery (org.apache.lucene.search.RegexpQuery)17 MatchAllDocsQuery (org.apache.lucene.search.MatchAllDocsQuery)16 PhraseQuery (org.apache.lucene.search.PhraseQuery)16 SpanTermQuery (org.apache.lucene.search.spans.SpanTermQuery)16 BoostQuery (org.apache.lucene.search.BoostQuery)15 TermRangeQuery (org.apache.lucene.search.TermRangeQuery)15 SpanMultiTermQueryWrapper (org.apache.lucene.search.spans.SpanMultiTermQueryWrapper)15 SpanNearQuery (org.apache.lucene.search.spans.SpanNearQuery)15 SpanQuery (org.apache.lucene.search.spans.SpanQuery)15 IndexReader (org.apache.lucene.index.IndexReader)14 ConstantScoreQuery (org.apache.lucene.search.ConstantScoreQuery)14