【问题标题】:Neo4j foreach clause to loop through elements of string arrayNeo4j foreach 子句循环遍历字符串数组的元素
【发布时间】:2021-09-22 13:50:56
【问题描述】:

我有一些包含字符串字段的节点。该字符串字段是一个 pk 列表,每个 pk 代表另一个节点的 pk。我想遍历这个字符串列表并将所有 pk 转换为它们各自的名称。例如:

MATCH (r:Recipe) RETURN r.ingredients_list AS ingredients_list LIMIT 1;

可能会返回这个:

ingredients_list
"Ingredients: 8572629, 1049724, 0494828, 0598371, 6168492, 0986423"

我想把它转换成这个:

ingredients_list
"Ingredients: flour, milk, eggs, butter, baking soda, sugar"

到目前为止,我已经设法获取字符串列表并将其拆分为一个数组:

WITH "Ingredients: " AS s MATCH (r:Recipes) WHERE r.ingredients_list ~= "Ingredients: .*"
WITH SPLIT(SUBSTRING(r.ingredients_list, SIZE(s), SIZE(r.ingredients_list)), ",")
AS string_arrays RETURN string_arrays;
string_arrays
["8572629", "1049724", "0494828", "0598371", "6168492", "0986423"]

而且我可以单独将每个 pk 与其对应的成分节点匹配并提取名称:

MATCH (g:Ingredient) WHERE g.pk = "0494828" RETURN g.name;

但我对如何遍历这些字符串数组感到困惑。我相信我想要像 reduce 函数这样循环遍历每个子数组,查询 :Ingredient 节点以找到正确的名称,然后进行字符串连接以再次将所有内容放入字符串中。但是累加器似乎只在节点上运行。 Neo 的FOREACH 也是如此。

是否有循环遍历字符串数组元素的函数?或者其他一些对字符串数组而不是节点数组的所有元素执行操作的neo函数?

【问题讨论】:

    标签: arrays string loops neo4j cypher


    【解决方案1】:
    WITH "Ingredients: " AS s
    MATCH (r:Recipes) WHERE r.ingredients_list ~=           "Ingredients: .*"
    // carry along the r to keep the recipes apart
    WITH r,split(substring(r.ingredients_list, size(s), size(r.ingredients_list))) AS string_arrays
    
    UNWIND string_arrays AS pk
    
    MATCH (g:Ingredient) WHERE g.pk = pk
    
    // return the Recipes node (or just its id) and the ingredient names
    RETURN r,collect(g.name) AS names
    

    【讨论】:

      【解决方案2】:

      您可能正在寻找UNWIND

      使用UNWIND,您可以将任何列表转换回单独的行。这些列表可以是传入的参数、以前的collect-ed 结果或其他列表表达式。 https://neo4j.com/docs/cypher-manual/4.3/clauses/unwind/

      使用UNWIND,您可以将string_arrays 转换为单独的行,执行MATCH 查找名称,最后将名称聚合为一个列表:

      UNWIND string_arrays AS pk
      MATCH (g:Ingredient) WHERE g.pk = pk
      RETURN collect(g.name) AS names
      

      但是,如果您已经有多个带有MATCH (r:Recipe) 的行,这可能会使列表混淆。所以你可能需要在subquery 中调用UNWIND

      WITH "Ingredients: " AS s
      MATCH (r:Recipes) WHERE r.ingredients_list ~= "Ingredients: .*"
      WITH split(substring(r.ingredients_list, size(s), size(r.ingredients_list))) AS string_arrays
      CALL {
        WITH string_arrays
        UNWIND string_arrays AS pk
        MATCH (g:Ingredient) WHERE g.pk = pk
        RETURN collect(g.name) AS names
      }
      RETURN names
      

      【讨论】:

        猜你喜欢
        • 2015-02-13
        • 1970-01-01
        • 2023-03-23
        • 2013-12-16
        • 1970-01-01
        • 2017-10-06
        • 1970-01-01
        • 2021-08-23
        • 1970-01-01
        相关资源
        最近更新 更多