Search code examples
neo4jneo4j-apoc

Getting topmost search result per group from Neo4j


I am using full text search capability of Neo4j to get nearest matching skills against an input list of search strings. Below in the cypher query.

UNWIND ["nursing care requirements", "relatives tutoring student nurses", "blood pressures", "emotional support", "intravenous infusions", "junior staff", "patient samples", "pulses", "workloads"] AS x
CALL db.index.fulltext.queryNodes("full-text-skills", x) YIELD node, score
RETURN x, node.name, score

It runs fine and return all the matching result (1000 rows for the above example). Now I want to fetch the top most matching skill in terms of the score property returned by db.index.fulltext.queryNodes (1 row per input item in the list). I tried adding limit after the return statement but it put limit on the whole output. What I really want is to put a limit of search results per item in the input list.


Solution

  • I finally got a solution to the above problem. We can use collect to gather results per group and depending on the limit we can get the results per group. Cypher query will be -

    UNWIND ["nursing care requirements", "relatives tutoring student nurses", "blood pressures", "emotional support", "intravenous infusions", "junior staff", "patient samples", "pulses", "workloads"] AS x
    CALL db.index.fulltext.queryNodes("full-text-skills", x) YIELD node, score
    RETURN x,collect(node.name)[0..3]