Search code examples
neo4jcypherpy2neo

Cypher query return undesirable result


I need to get texts and save them to Neo4j. After that, I separate each word of that text and create a [:NEXT] relationship between them indicating the word that comes after another one and a [:CONTAINS] relationship indicating that the text contains that word. Finally I try to get the word in the text that has more relations [:NEXT] but not in the whole database. Only in the given text.

Unfortunatelly I just get the sum of the whole database.

The query is:

query = '''
        WITH split("%s"," ") as words 
        MERGE (p:Post {id: '%s', text: '%s'})
        WITH p, words
        UNWIND range(0,size(words)-2) as idx
        MERGE (w1:Word {name:words[idx]})
        MERGE (w2:Word {name:words[idx+1]})
        MERGE (w1)-[:NEXT]->(w2)
        MERGE (p)-[:CONTAINS]->(w2)
        MERGE (p)-[:CONTAINS]->(w1)
        WITH p
        MATCH (p)-[c:CONTAINS]->(w:Word)
        MATCH ()-[n1:NEXT]->(:Word {name: w.name})<-[:CONTAINS]-(p)
        MATCH (p)-[:CONTAINS]-(:Word {name: w.name})-[n2:NEXT]->()
        WITH COUNT(n1) + COUNT(n2)AS score, w.name AS word, p.text AS post, p.id AS _id
        RETURN post, word, score, _id;
        '''  %(text, id, text)

I just can't find out the problem here.

Thanks!


Solution

  • My solution is:

    query = '''
        WITH split("%s"," ") AS words 
        MERGE (p:Post {id: "%s", text:"%s"})
        WITH p, words 
        UNWIND range(0,size(words)-2) as idx
        MERGE (w1:Word {name:words[idx]})
        MERGE (w2:Word {name:words[idx+1]})
        MERGE (w1)-[n:NEXT]->(w2)
        ON MATCH SET n.count = n.count + 1
        ON CREATE SET n.count = 1
        MERGE (p)-[:CONTAINS]->(w2)
        MERGE (p)-[:CONTAINS]->(w1)
        '''  %(text, id, text)