Showing results for 
Search instead for 
Did you mean: 

Select one node, when multiple nodes have same property

Node Clone

Hello all,

I am working the below schema :

I want to fetch the Questions, but in case if the two questions have same QuestionLibraryId, I want either of the two returned.

So in the above scenario, I should only get one question in the output.

Any help would be really appreciated.


You can aggregate the questions by the library ID and take the head() of the resulting list:

... // assume q is in scope for the matched questions
WITH q.QuestionLibraryId as qID, collect(q) as questions
WITH head(questions) as question

Note that the questions list is all the questions for a given question library ID, so if for a given ID there is only one question, then the questions list will be size 1 for that row. After the last WITH you will have a row per question, and no two questions across those rows will share the same QuestionLibraryId.

Of course you'll need to adjust as needed for whatever else you have in scope.

If there can be many questions with the same id, and you want a random one, then if you have APOC Procedures installed you can use the apoc.coll.randomItem() function to take one from the list at random.

Thanks a ton @andrew.bowman .
This works perfectly.