使用cypher / neo4j比较数组值

时间:2013-12-09 23:13:18

标签: neo4j cypher

我有一个成员图表和他们看过的项目。

此数据将用于根据类似成员查看的项目推荐项目。我想根据项目颜色的相似程度对项目进行排序。颜色以数组形式存储在项目中([“红色”,“蓝色”,“绿色”])。在cypher中有没有办法比较数组,看看它们有多少共同的元素?

2 个答案:

答案 0 :(得分:8)

给定两个节点n和m,它们看起来像:

CREATE ({id: 1, color: ["red", "blue", "green", "yellow"]})
CREATE ({id: 2, color: ["red", "blue", "green", "white"]})

您可以这样做:

MATCH n, m
WHERE n.id = 1 AND m.id = 2
RETURN length(FILTER(x in n.color WHERE x in m.color))

FILTER函数遍历n.color数组,将当前值绑定到x(由我任意选择,可能不同)。对每个x in m.color值检查谓词(x),如果它的计算结果为true,则将该元素推送到FILTER返回的新数组中。您可以将其保留在那里以查看两个数组的交集(在本例中为红色,蓝色和绿色),或将其包装在length函数中以查看两个节点之间共享的颜色数(3在这种情况下)。

在此处查看完整的FILTER文档:http://docs.neo4j.org/chunked/milestone/query-functions-collection.html#functions-filter

答案 1 :(得分:1)

上面给出的解决方案是好的。但是在新版本(4.0)中,他们进行了一些更改。 不建议使用Filter()方法,而list()是

仅限在路径上使用

Version 4.0

他们将过滤器替换为List comprehension 因此,不要使用上面的代码

from bokeh.io import curdoc
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure
from bokeh.models.widgets import Button
from bokeh.layouts import column, widgetbox

import time
import numpy as np
import datetime as dt
import threading
import sys


def blocking_task():
    while threading.main_thread().is_alive():
        time.sleep(0.1)
    else:
        print('exiting child thread')


def button_callback():
    sys.exit()


def update():
    data = np.random.rand()
    source.stream(dict(time=[dt.datetime.now()], data=[data]), 100)


doc = curdoc()

source = ColumnDataSource(dict(time=[], data=[]))
fig = figure(x_axis_type='datetime', plot_width=800, plot_height=400)
fig.line(x='time', y='data', source=source)

button = Button(label="Stop", button_type="success")
button.on_click(button_callback)

doc.add_root(column([fig, widgetbox(button, align="center")], sizing_mode='stretch_both'))
doc.add_periodic_callback(callback=update, period_milliseconds=100)

thread = threading.Thread(target=blocking_task)
thread.start()

我建议您使用这个。

MATCH n, m
WHERE n.id = 1 AND m.id = 2
RETURN length(FILTER(x in n.color WHERE x in m.color))