[英]How to implement Gremlin query corresponding to Neo4j cypher query?
[英]Need help and Want to know how we can write this type of Neo4j Cypher query into Gremlin query?
MATCH (m:movie)-[has_directed_by:has_directed]->(director:Director)
OPTIONAL MATCH(director)-[has_name:has_name]->(directorName:DirectorName)
OPTIONAL MATCH(director)-[has_type:has_type]->(directionType:DirectionType)
OPTIONAL MATCH(director)-[has_language:has_language]->(directionLanguage:DirectionLangugaue)
OPTIONAL MATCH (director)-[has_script:has_script]->(script:Script)
OPTIONAL MATCH (m)-[has_songs:has_songs]->(songs:Songs)
WITH m,has_directed_by,director,has_name,directorName,has_type,directionType,
has_language,directionLanguage,has_script,script order by m.id ASC
RETURN distinct m,collect(has_directed_by),collect(director),collect(has_name),
collect(directorName),collect(has_type),collect(directionType),collect(has_language),collect(directionLanguage),collect(has_script),collect(script),collect(has_songs),collect(songs);
如何在 cypher 中為此類硬查詢編寫 gremlin 查詢? 請幫忙。 我想知道我們如何在 gremlin 中一次又一次地引用那個“m”和“director”。
例子:
g.V().
hasLabel('movie').as('m').
outE('has_directed').
inV().
hasLabel('Director').as('director')
但是在接下來的圖遍歷中需要引用那個'm'和'director'。 請幫忙
所以,沒有雙關語的意思,對於這樣的轉換,最好一次采取一個步驟。 第一行大致相當於:
g.V().
hasLabel('movie').as('m').
outE('has_directed').
inV().
hasLabel('Director').as('director')
但是,通常可以使用更慣用的 Gremlin,它使用圍繞諸如project
之類as
步驟構建的方法來避免許多步驟。 如果需要從邊緣檢索屬性,則只需要outE
和inV
步驟。 否則只要out
就足夠了。
Gremlin 也有一個match
步驟,允許您以類似的聲明式樣式轉換 Cypher 查詢,但我更喜歡使用其他 Gremlin 步驟並在大多數情況下避免match
。
在 Gremlin 中有一個optional
步驟,但也有coalesce
和choose
步驟,允許您編寫一種IF...THEN...ELSE
類型的查詢,這相當於OPTIONAL MATCH
就distinct
而言,等效的dedup
步驟是去重
在 Gremlin 中將一系列可選事物組合在一起的一種方法是使用union
步驟。
Gremlin 中的fold
步驟的使用方式與 Cypher 中的collect
步驟類似。
由於我沒有你的數據集,我使用 air-routes 數據集來演示OPTIONAL MATCH
的等價物,本質上是在沒有結果時使用fold
步驟生成一個空列表。
gremlin> g.V('0','44').
......1> project('start','neighbors').
......2> by(id).
......3> by(out().fold())
==>[start:0,neighbors:[]]
==>[start:44,neighbors:[v[8],v[13],v[20],v[31]]]
如上所述, fold
步驟類似於 Cypher collect
function。在上面的示例中,當沒有匹配時,鄰居由一個空列表表示。 您可以by
需要為project
步驟設置盡可能多的子部分(鍵名和調制器),以表示所有可選案例。
當然,有很多方法可以編寫查詢,具體取決於您希望如何表示未找到任何內容的情況。 如果您更喜歡使用默認值而不是空列表,則可以使用coalesce
步驟。
gremlin> g.V('0','44').
......1> project('start','neighbors').
......2> by(id).
......3> by(coalesce(out(),constant('None')))
==>[start:0,neighbors:None]
==>[start:44,neighbors:v[8]]
對您的數據集使用類似的模式,基本構建塊可能是:
g.V().
hasLabel('Movie').
project('movie','director').
by(valueMap().with(WithOptions.tokens)).
by(out('has_directed').valueMap().with(WithOptions.tokens).fold())
valueMap
步驟將返回頂點(或邊)的所有屬性。 我將其添加到我的示例中以模擬 Cypher 將執行的操作。 默認情況下(沒有像valueMap
這樣的步驟)Gremlin 在許多情況下只會返回沒有其屬性的頂點。 with
告訴 Gremlin 在結果中也包含 ID 和 label。 這等同於棄用的形式valueMap(true)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.