Reetish Chand
Reetish Chand

Reputation: 103

Searching properties in neo4j queries

There is a node Person which consists of 2 properties : firstName, lastName . The user may input firstName or lastName or both. If both names are specified there is no guarantee that the names are in firstName and lastName order . For example : if a name is sherlock holmes , the user may give holmes sherlock or only sherlock or holmes or sherlock holmes. In all these cases we must get the sherlock holmes node. If no input is specified then all the Person nodes are to be returned.

I tried the following query :

Match (n : Person )
where n.firstName+" "+n.lastName ={1} or n.lastName+" "+n.firstName={1}  
return n

Where {1} is the name.

Can anyone help me out !!

Upvotes: 1

Views: 181

Answers (1)

cybersam
cybersam

Reputation: 67044

[UPDATED twice]

Something like the following should work.

WITH SPLIT($name, ' ') AS parts
WITH parts, SIZE(parts)=1 AS one_part
MATCH (n: Person)
WHERE
  parts IS NULL OR
  (n.firstName=parts[0] AND (one_part OR n.lastName=parts[1])) OR
  (n.lastName=parts[0] AND (one_part OR n.firstName=parts[1])) OR
  (parts[0] = '' AND NOT EXISTS(n.firstName) AND NOT EXISTS(n.lastName))
RETURN n

Special cases:

  • If the name parameter is NULL, then all Person nodes are returned.
  • If the name parameter is an empty string, then this query will match any Person node having an empty string as the firstName or lastName value, or having neither of those properties.

Upvotes: 2

Related Questions