Search code examples
neo4jcypher

Efficient search of Neo4j relationships by property value


In Neo4j, I need to find all relationships with a given property value, independently on the relationship type:

WITH ["1651365", "1188654", "1151147", ...] AS relIds
MATCH ()-[r]->() WHERE r.myId IN relIds
RETURN TYPE(r) AS type, properties ( r ) AS props;

This query works, but it's very slow. If I profile it, I see it's based on a full scan (of 14M relationships).

The problem is there is no way to define an index on all the relationship types (I can do the same with a list of types and the engine will use indexes defined for myId).

Is there a solution? When using elementId(), the engine does a seek operation and it's very fast, but the documentation discourages it (they say internal IDs are reused after deletion).


Solution

  • You can create a fulltext index on properties of multiple relationship types. For example:

    CREATE FULLTEXT INDEX ft_rel_myId IF NOT EXISTS FOR ()-[r:A|B|C|D|E]-() ON EACH [r.myId];
    

    With that index, you can do a fulltext search:

    WITH apoc.text.join(["1651365", "1188654", "1151147"], ' OR ') AS ft_query
    CALL db.index.fulltext.queryRelationships("ft_rel_myId", ft_query) YIELD relationship, score
    WHERE score = 1.0
    RETURN relationship.type AS type, properties (relationship) AS props;