简体   繁体   中英

Cypher Neo4j query

I am developing some kind of social trivia game where my main DB is Neo4j. I am having a hard time in a specific use-case.

I have Challenge node with two Opponents nodes related:

(opponent1)-[:OPPONENT]->(challenge)<-[:OPPONENT]-(opponent2)

The Challenge relate to Subject node:

challenge-[:subject]->subject

Each subject relate to many questions:

subject-[:HAS]->question

If opponent answered a specific question before the bellow relation will be exist:

opponent-[:ANSWER]->question

The use-case: I need to retrieve X questions (which never been answered by both opponents) for the challenge

I have the following Cypher query:

START challenge=node({0}) , subject=node({1}) 
MATCH (opponent1)-[:OPPONENT]->(challenge)<-[:OPPONENT]-(opponent2) 
WITH opponent1,opponent2,subject
MATCH (subject)-[:HAS]->(question) 
WHERE  length(opponent1-[:ANSWER]->question) = 0 and length(opponent2-[:ANSWER]->question) = 0 
return question limit {2}

The above query works fine and retrieve the possible questions for the challenge.

The problem is that the questions are retrieved consequently and not randomly.

Explanation: Each question related to template node which has category property.

question-[:TEMPLATE]->template

The questions created in the first place by template which mean all the questions from specific category has sequenced ID in the DB therefore the above query retrieves questions from the same category.

I want to be able to retrieve challenge questions randomly. Also, is the query structure is correct from a performance perspective?

i'm not aware of a native way of how to get a random result, there is smting already asked about it here: neo4j: Is there a way/how to select random nodes?

about the query, depends on data, but i would try rather this:

START challenge=node({0}) , subject=node({1})
MATCH (opponent1)-[:OPPONENT]->(challenge)<-[:OPPONENT]-(opponent2)
WITH opponent1,opponent2,subject
MATCH (subject)-[:HAS]->(question)
WHERE not(opponent1-[:ANSWER]->question) and not (opponent2-[:ANSWER]->question)
return question limit {2} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM