我有一个带有这种模式的neo4j数据库(:用户) - [:ANSWER_TO_QUESTION] - >(:问题)。
在我的应用中有一些问题和一些用户节点。用户将回答问题,答案将保存用户和问题之间的关系。
用户可以跳过问题,答案将在与问题的关系上保存为空。
每个问题都有一个答案循环时间,用于重新询问问题,如果用户回答问题,没有答案循环时间,如果用户没有回答问题则重新询问问题。
现在我想查询一个特殊用户没有询问或没有回答的问题,并且没有通过或回答无应答周期,并且答案周期已过。按优先顺序排序,然后返回一个问题。
我尝试使用union进行查询但是我不能在总结果上返回限制1。因此查询将返回3个问题,每个联合查询一个。
MATCH (n:Users {user_name:$user_name}),(q:Questions)
Where NOT (n)-[:ANSWERED_OF_QUESTION]->(q)
return q as question
ORDER BY question.priority DESC
LIMIT 1
UNION MATCH (n:Users {user_name:$user_name})-[r:ANSWERED_OF_QUESTION]->(q:Questions)
Where r.answer is null and r.created+q.no_answer_cycle < $now_time
RETURN q as question
ORDER BY question.priority DESC
LIMIT 1
UNION MATCH (n:Users {user_name:$user_name})-[r:ANSWERED_OF_QUESTION]->(q:Questions
Where r.answer is not null and r.created+q.answer_cycle < $now_time
RETURN q as question
ORDER BY question.priority DESC
LIMIT 1
我尝试过OPTIONAL MATCH和CASE,但没有得到我的结果。任何帮助?
答案 0 :(得分:1)
以这种方式简化它怎么样?
MATCH (q:Questions)
WHERE NOT EXISTS ((:Users {user_name:$user_name})-[:ANSWERED_OF_QUESTION]->(q))
OPTIONAL MATCH (n:Users {user_name:$user_name})-[r:ANSWERED_OF_QUESTION]->(q)
WHERE (r.answer is null and r.created+q.no_answer_cycle < $now_time)
OR (r.answer is not null and r.created+q.answer_cycle < $now_time)
RETURN q as question
ORDER BY question.priority DESC
LIMIT 1
答案 1 :(得分:1)
我得到了答案:
call apoc.cypher.run("MATCH (n:Users {user_name:$user_name}),(q:Questions)
Where NOT (n)-[:ANSWERED_OF_QUESTION]->(q)
return q as question
ORDER BY question.priority DESC
LIMIT 1 UNION MATCH (n:Users {user_name:$user_name})-[r:ANSWERED_OF_QUESTION]->(q:Questions)
Where r.answer is null
RETURN q as question
ORDER BY question.priority DESC
LIMIT 1
UNION MATCH (n:Users {user_name:$user_name})-[r:ANSWERED_OF_QUESTION]->(q:Questions)
Where r.answer is not null
RETURN q as question
ORDER BY question.priority DESC
LIMIT 1",{user_name:"saeed@saeed.com"})
yield value
RETURN value
ORDER BY value.question.priority
DESC LIMIT 1'
编辑: 第二个解决方案:从lokesh
启发MATCH (q:Questions), (n:Users {user_name:$user_name})
OPTIONAL MATCH (n)-[r:ANSWERED_OF_QUESTION]->(q)
WHERE (r.answer is null )
OR (r.answer is not null )
RETURN q as question
ORDER BY question.priority DESC
LIMIT 1
有任何改进建议吗?