Search in sources :

Example 1 with ValueContext

use of org.neo4j.index.lucene.ValueContext 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 2 with ValueContext

use of org.neo4j.index.lucene.ValueContext in project graphdb by neo4j-attic.

the class LuceneBatchInserterIndex method add.

public void add(long entityId, Map<String, Object> properties) {
    try {
        Document document = identifier.entityType.newDocument(entityId);
        for (Map.Entry<String, Object> entry : properties.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            boolean isValueContext = value instanceof ValueContext;
            value = isValueContext ? ((ValueContext) value).getCorrectValue() : value;
            for (Object oneValue : IoPrimitiveUtils.asArray(value)) {
                oneValue = isValueContext ? oneValue : oneValue.toString();
                type.addToDocument(document, key, oneValue);
                if (createdNow) {
                    // If we know that the index was created this session
                    // then we can go ahead and add stuff to the cache directly
                    // when adding to the index.
                    addToCache(entityId, key, oneValue);
                }
            }
        }
        writer.addDocument(document);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Also used : ValueContext(org.neo4j.index.lucene.ValueContext) IOException(java.io.IOException) Document(org.apache.lucene.document.Document) HashMap(java.util.HashMap) Map(java.util.Map)

Example 3 with ValueContext

use of org.neo4j.index.lucene.ValueContext in project graphdb by neo4j-attic.

the class TestLuceneIndex method testRemoveNumericValues.

@Test
public void testRemoveNumericValues() {
    Index<Node> index = nodeIndex("numeric2", LuceneIndexImplementation.EXACT_CONFIG);
    Node node1 = graphDb.createNode();
    Node node2 = graphDb.createNode();
    String key = "key";
    index.add(node1, key, new ValueContext(15).indexNumeric());
    index.add(node2, key, new ValueContext(5).indexNumeric());
    index.remove(node1, key, new ValueContext(15).indexNumeric());
    assertThat(index.query(NumericRangeQuery.newIntRange(key, 0, 20, false, false)), contains(node2));
    index.remove(node2, key, new ValueContext(5).indexNumeric());
    assertThat(index.query(NumericRangeQuery.newIntRange(key, 0, 20, false, false)), isEmpty());
    restartTx();
    assertThat(index.query(NumericRangeQuery.newIntRange(key, 0, 20, false, false)), isEmpty());
    index.add(node1, key, new ValueContext(15).indexNumeric());
    index.add(node2, key, new ValueContext(5).indexNumeric());
    restartTx();
    assertThat(index.query(NumericRangeQuery.newIntRange(key, 0, 20, false, false)), contains(node1, node2));
    index.remove(node1, key, new ValueContext(15).indexNumeric());
    assertThat(index.query(NumericRangeQuery.newIntRange(key, 0, 20, false, false)), contains(node2));
    restartTx();
    assertThat(index.query(NumericRangeQuery.newIntRange(key, 0, 20, false, false)), contains(node2));
}
Also used : ValueContext(org.neo4j.index.lucene.ValueContext) Node(org.neo4j.graphdb.Node) Test(org.junit.Test)

Example 4 with ValueContext

use of org.neo4j.index.lucene.ValueContext in project neo4j by neo4j.

the class TestLuceneIndex method doubleNumericPropertyValueForAllNodesWithLabel.

private void doubleNumericPropertyValueForAllNodesWithLabel(Index<Node> index, String numericProperty, Label label) {
    try (Transaction transaction = graphDb.beginTx()) {
        ResourceIterator<Node> nodes = graphDb.findNodes(label);
        nodes.stream().forEach(node -> {
            node.setProperty(numericProperty, (Integer) node.getProperty(numericProperty) * 2);
            index.remove(node, numericProperty);
            index.add(node, numericProperty, new ValueContext(node.getProperty(numericProperty)).indexNumeric());
        });
        transaction.success();
    }
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ValueContext(org.neo4j.index.lucene.ValueContext) Transaction(org.neo4j.graphdb.Transaction) Node(org.neo4j.graphdb.Node)

Example 5 with ValueContext

use of org.neo4j.index.lucene.ValueContext in project neo4j by neo4j.

the class TestLuceneIndex method queryIndexWithSortByNumericAfterSamePropertyUpdate.

@Test
public void queryIndexWithSortByNumericAfterSamePropertyUpdate() {
    Index<Node> index = nodeIndex(stringMap());
    commitTx();
    String numericProperty = "PRODUCT_ID";
    Label updatableIndexesProperty = Label.label("updatableIndexes");
    try (Transaction transaction = graphDb.beginTx()) {
        for (int i = 0; i < 15; i++) {
            Node node = graphDb.createNode(updatableIndexesProperty);
            node.setProperty(numericProperty, i);
            index.add(node, numericProperty, new ValueContext(i).indexNumeric());
        }
        transaction.success();
    }
    doubleNumericPropertyValueForAllNodesWithLabel(index, numericProperty, updatableIndexesProperty);
    queryAndSortNodesByNumericProperty(index, numericProperty, i -> i * 2);
}
Also used : ValueContext(org.neo4j.index.lucene.ValueContext) Transaction(org.neo4j.graphdb.Transaction) Node(org.neo4j.graphdb.Node) Label(org.neo4j.graphdb.Label) Test(org.junit.Test)

Aggregations

ValueContext (org.neo4j.index.lucene.ValueContext)10 Node (org.neo4j.graphdb.Node)9 Test (org.junit.Test)8 Transaction (org.neo4j.graphdb.Transaction)5 Label (org.neo4j.graphdb.Label)2 IOException (java.io.IOException)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 Map (java.util.Map)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 Document (org.apache.lucene.document.Document)1 Term (org.apache.lucene.index.Term)1 TermQuery (org.apache.lucene.search.TermQuery)1 WildcardQuery (org.apache.lucene.search.WildcardQuery)1 IndexManager (org.neo4j.graphdb.index.IndexManager)1 LuceneBatchInserterIndexProviderNewImpl (org.neo4j.index.impl.lucene.legacy.LuceneBatchInserterIndexProviderNewImpl)1 QueryContext (org.neo4j.index.lucene.QueryContext)1 LuceneBatchInserterIndexProvider (org.neo4j.index.lucene.unsafe.batchinsert.LuceneBatchInserterIndexProvider)1