Home > front end >  Cypher / Neo4j query that gets a nodes nodes with specific multiple relationships
Cypher / Neo4j query that gets a nodes nodes with specific multiple relationships

Time:01-02

i am working on app organizer app. It has items with labels Item and tags with label Tags. Items can have multiple labels up to five.

(i:Item)-[:HAS]->(t:Tag)

I am using a php to do that so ideally i would be able to concatenate the query :

$tags = $this->getParam("tags"); // split by comma or some separator
        
if ($tags != null) {
      $arrayTags =  explode(";", $tags ,5);

      $queryAddTagSpecifiers = "";

      for ($i=0;$i<count($arrayTags);$i  ) {
          $queryAddTagSpecifiers.= " MATCH (t:Tag {name:'".$arrayTags[$i]."'})<-[:HAS]-(i:Item)";
       }

       $query = "MATCH (t:Tag)<-[:HAS]-(i:Item)-[:OWNED]->(u:User) 
               ".$queryAddTagSpecifiers."
                 WHERE u.id='" . $this->userId . "' RETURN i";
       echo $query;

   }

I am trying to write a query MATCH to get an items with multiple Tags. For single tag it works.

for example document10 has tag house and image222

I tried multiple variants of this :

MATCH (i:Item)-[:OWNED]->(u:User) MATCH (t:Tag {name:'house'})<-[:HAS]-(i:Item) MATCH (t:Tag {name:'image222'})<-[:HAS]-(i:Item) WHERE u.id='1640793954DANYXV4RW8EFZLIJNUMC' RETURN i

I also used WHERE t.name='house AND t.name='image222' but no luck, probably because they are mutually exclusive.

Any help is appreciated.

CodePudding user response:

If you have tags with names 'Tag1', 'Tag2', 'Tag3', 'Tag4' and you want to find items that have both 'Tag1' and 'Tag3', you can do

WITH ['Tag1','Tag3'] AS tags
MATCH (i:Item)
WHERE ALL(tag IN tags WHERE tag IN [(i)-[:HAS]->(itemTag) | itemTag.name])
RETURN i

in which this part

[(i)-[:HAS]->(itemTag) | itemTag.name]

is the collection of tags of a specific item

  • Related