Skip to content

Instantly share code, notes, and snippets.

@CoralineAda
Created December 29, 2014 14:31
Show Gist options
  • Save CoralineAda/8ed2d029069eddb8989c to your computer and use it in GitHub Desktop.
Save CoralineAda/8ed2d029069eddb8989c to your computer and use it in GitHub Desktop.
Neo4J query question

I have a relation like this:

context-[EXPRESSED_AS]->root

Assume that I have two contexts. The first has roots with base_forms of "temperature", "cool" and "hot". The second has roots with base_forms of "cool" and "hot". I want to find all contexts, sorted by the number of matches for the set ["cool", "temperature"].

I attempted it using this Cypher query, which doesn't work since the IN operator returns true or false instead of the matches:

"MATCH (w:`context`), s-[EXPRESSED_AS]->n1 WHERE n1.base_form in ["cool", "temperature"] WITH s, COUNT(n1.base_form in ["cool", "temperature"]) AS rootCount RETURN s.name, rootCount ORDER BY rootCount

Any help is appreciated!

@ikwattro
Copy link

Does this query fits your needs ?

MATCH (n:Context)
OPTIONAL MATCH (n)-[:EXPRESSED_AS]->(r)
WHERE r.base_form IN ["cool","temperature"]
RETURN n, count(r) as c
ORDER BY c DESC

Result :

id  1b9cd24c-26ea-3fc3-a70c-2621df260b06 65
id  17163e02-ffe2-35fc-8e24-403159be141b 65
id  c6784e59-416c-38f9-a8b2-0a6f7f02e656 64
id  61ce7b9a-b121-3a43-ba59-05f8d00d519b 63
id     3302aae1-78d9-37e4-8bc3-b05d6105b28d 0

@CoralineAda
Copy link
Author

I need to get the contexts back with the counts. I amended your suggestion to this:

MATCH (w:`context`) OPTIONAL MATCH s-[EXPRESSED_AS]->n WHERE n.base_form in ["cool", "temperature"] RETURN s, count(n) as c ORDER BY c desc

This returns the contexts in the expected order, but their c values are the same.

@ikwattro
Copy link

Mmmh it seems like I can't visualize your model then.

2 contexts

(context1)-[:EXPRESSED_AS]->(root {base_form:"cool"})
(context1)-[:EXPRESSED_AS]->(root {base_form:"temperature"})
(context1)-[:EXPRESSED_AS]->(root {base_form:"hot"})
(context2)-[:EXPRESSED_AS]->(root {base_form:"cool"})
(context2)-[:EXPRESSED_AS]->(root {base_form:"hot"})

Is it like this ?

If yes, then your context will only match 1 time the map cool,temperature ?

@CoralineAda
Copy link
Author

I'm basically looking for the closest matches with their counts, based on the number of 'hits' from roots in the set.

(I've moved the question to http://stackoverflow.com/questions/27691969/neo4j-query-on-number-of-matches-in-a-set)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment