Index existing relationships in neo4j

2019-08-25 10:33发布

问题:

Is it possible to add index on existing relationships. More specifically I have a relationship called Relatadness with one property called score(score is double) and I want to index it (with java or through the web client). How can do that? thanks in advance

回答1:

Since you already have the relationships, you'll have to iterate through all of them. This code example will create an index called RelatadnessIndex, and store the relationship in the index under a key of score:

    GlobalGraphOperations ggo = GlobalGraphOperations.at(db);
    Index<Relationship> relatadnessIndex = db.index().forRelationships("RelatadnessIndex");
    for (Relationship r : ggo.getAllRelationships()) {
        if (r.getType().name().equals("Relatadness")) {
            double score = (double) r.getProperty("score");
            relatadnessIndex.add(r, "score", score);
        }
    }

Note that by default Neo4j/Lucene will index the value as a String, so doing numeric range searches won't work. If you want to have it stored as a Numeric, you'll need to change to add to be this:

relatadnessIndex.add(r, "score", new ValueContext( score ).indexNumeric() );