将数据加载到 Neo4j 中

2024-08-19 0 183

在上一篇博客中,我们了解了如何使用 2 个插件 apoc 和图形数据科学库 – gds 在本地安装和设置 neo4j。在这篇博客中,我将获取一个玩具数据集(电子商务网站中的产品)并将其存储在 neo4j 中。

为 neo4j 分配足够的内存

在开始加载数据之前,如果您的用例中有大量数据,请确保为 neo4j 分配了足够的内存。为此:

  • 点击打开右侧的三个点

将数据加载到 Neo4j 中

    点击

  • 打开文件-> 配置

将数据加载到 Neo4j 中

    点击

  • neo4j.conf

将数据加载到 Neo4j 中

    在neo4j.conf中搜索

  • heap,取消第77、78行的注释,并将256m更改为2048m,这样可以确保为neo4j中的数据存储分配2048mb。

将数据加载到 Neo4j 中

 

创建节点

  • 图有两个主要组成部分:节点和关系,让我们先创建节点,然后再建立关系。

  • 我正在使用的数据在这里 – data

  • 使用这里提供的requirements.txt来创建一个Python虚拟环境-requirements.txt

  • 让我们定义各种函数来推送数据。

  • 导入必要的库

1

2

3

import pandas as pd

from neo4j import graphdatabase

from openai import openai

1

2

client = openai(API_key="")

product_data_df = pd.read_csv('../data/product_data.csv')

1

2

3

4

5

6

7

8

9

def get_embedding(text):

    """

    used to generate embeddings using openai embeddings model

    :param text: str - text that needs to be converted to embeddings

    :return: embedding

    """

    model = "text-embedding-3-small"

    text = text.replace("\n", " ")

    return client.embeddings.create(input=[text], model=model).data[0].embedding

    根据我们的数据集,我们可以有两个唯一的节点标签,

  • category:产品类别,product:产品名称。让我们创建类别标签,neo4j 提供了一种称为属性的东西,您可以将它们想象为特定节点的元数据。这里 name 和 embedding 是属性。因此,我们将类别名称及其相应的嵌入存储在数据库中。

1

2

3

4

5

6

7

8

9

10

11

12

13

def create_category(product_data_df):

    """

    used to generate queries for creating category nodes in neo4j

    :param product_data_df: pandas dataframe - data

    :return: query_list: list - list containing all create node queries for category

    """

    cat_query = """create (a:category {name: '%s', embedding: %s})"""

    distinct_category = product_data_df['category'].unique()

    query_list = []

    for category in distinct_category:

        embedding = get_embedding(category)

        query_list.append(cat_query % (category, embedding))

    return query_list

    类似地,我们可以创建产品节点,这里的属性是

  • namedescrIPtionpricewarranty_periodavailable_stockreview_ ratingproduct_release_dateembedding

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

def create_product(product_data_df):

    """

    used to generate queries for creating product nodes in neo4j

    :param product_data_df: pandas dataframe - data

    :return: query_list: list - list containing all create node queries for product

    """

    product_query = """create (a:product {name: '%s', description: '%s', price: %d, warranty_period: %d,

    available_stock: %d, review_rating: %f, product_release_date: date('%s'), embedding: %s})"""

    query_list = []

    for idx, row in product_data_df.iterrows():

        embedding = get_embedding(row['product name'] + " - " + row['description'])

        query_list.append(product_query % (row['product name'], row['description'], int(row['price (inr)']),

                                           int(row['warranty period (years)']), int(row['stock']),

                                           float(row['review rating']), str(row['product release date']), embedding))

    return query_list

    现在让我们创建另一个函数来执行上述两个函数生成的查询。适当更新您的用户名和密码

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

def execute_bulk_query(query_list):

    """

    executes queries is a list one by one

    :param query_list: list - list of cypher queries

    :return: none

    """

    url = "bolt://localhost:7687"

    auth = ("neo4j", "neo4j@123")

    with graphdatabase.driver(url, auth=auth) as driver:

        with driver.session() as session:

            for query in query_list:

                try:

                    session.run(query)

                except exception as error:

                    print(f"error in executing query - {query}, error - {error}")

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

import pandas as pd

from neo4j import graphdatabase

from openai import openai

client = openai(api_key="")

product_data_df = pd.read_csv('../data/product_data.csv')

def preprocessing(df, columns_to_replace):

    """

    used to preprocess certain column in dataframe

    :param df: pandas dataframe - data

    :param columns_to_replace: list - column name list

    :return: df: pandas dataframe - processed data

    """

    df[columns_to_replace] = df[columns_to_replace].apply(lambda col: col.str.replace("'s", "s"))

    df[columns_to_replace] = df[columns_to_replace].apply(lambda col: col.str.replace("'", ""))

    return df

def get_embedding(text):

    """

    used to generate embeddings using openai embeddings model

    :param text: str - text that needs to be converted to embeddings

    :return: embedding

    """

    model = "text-embedding-3-small"

    text = text.replace("\n", " ")

    return client.embeddings.create(input=[text], model=model).data[0].embedding

def create_category(product_data_df):

    """

    used to generate queries for creating category nodes in neo4j

    :param product_data_df: pandas dataframe - data

    :return: query_list: list - list containing all create node queries for category

    """

    cat_query = """create (a:category {name: '%s', embedding: %s})"""

    distinct_category = product_data_df['category'].unique()

    query_list = []

    for category in distinct_category:

        embedding = get_embedding(category)

        query_list.append(cat_query % (category, embedding))

    return query_list

def create_product(product_data_df):

    """

    used to generate queries for creating product nodes in neo4j

    :param product_data_df: pandas dataframe - data

    :return: query_list: list - list containing all create node queries for product

    """

    product_query = """create (a:product {name: '%s', description: '%s', price: %d, warranty_period: %d,

    available_stock: %d, review_rating: %f, product_release_date: date('%s'), embedding: %s})"""

    query_list = []

    for idx, row in product_data_df.iterrows():

        embedding = get_embedding(row['product name'] + " - " + row['description'])

        query_list.append(product_query % (row['product name'], row['description'], int(row['price (inr)']),

                                           int(row['warranty period (years)']), int(row['stock']),

                                           float(row['review rating']), str(row['product release date']), embedding))

    return query_list

def execute_bulk_query(query_list):

    """

    executes queries is a list one by one

    :param query_list: list - list of cypher queries

    :return: none

    """

    url = "bolt://localhost:7687"

    auth = ("neo4j", "neo4j@123")

    with graphdatabase.driver(url, auth=auth) as driver:

        with driver.session() as session:

            for query in query_list:

                try:

                    session.run(query)

                except exception as error:

                    print(f"error in executing query - {query}, error - {error}")

# preprocessing

product_data_df = preprocessing(product_data_df, ['product name', 'description'])

# create category

query_list = create_category(product_data_df)

execute_bulk_query(query_list)

# create product

query_list = create_product(product_data_df)

execute_bulk_query(query_list)

 

建立关系

    我们将在

  • category 和 product 之间创建关系,该关系的名称为 category_contains_product

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

from neo4j import GraphDatabase

import pandas as pd

product_data_df = pd.read_csv('../data/product_data.csv')

def preprocessing(df, columns_to_replace):

    """

    Used to preprocess certain column in dataframe

    :param df: pandas dataframe - data

    :param columns_to_replace: list - column name list

    :return: df: pandas dataframe - processed data

    """

    df[columns_to_replace] = df[columns_to_replace].apply(lambda col: col.str.replace("'s", "s"))

    df[columns_to_replace] = df[columns_to_replace].apply(lambda col: col.str.replace("'", ""))

    return df

def create_category_food_relationship_query(product_data_df):

    """

    Used to create relationship between category and products

    :param product_data_df: dataframe - data

    :return: query_list: list - cypher queries

    """

    query = """MATCH (c:Category {name: '%s'}), (p:Product {name: '%s'}) CREATE (c)-[:CATEGORY_CONTAINS_PRODUCT]->(p)"""

    query_list = []

    for idx, row in product_data_df.iterrows():

        query_list.append(query % (row['Category'], row['Product Name']))

    return query_list

def execute_bulk_query(query_list):

    """

    Executes queries is a list one by one

    :param query_list: list - list of cypher queries

    :return: None

    """

    url = "bolt://localhost:7687"

    auth = ("neo4j", "neo4j@123")

    with GraphDatabase.driver(url, auth=auth) as driver:

        with driver.session() as session:

            for query in query_list:

                try:

                    session.run(query)

                except Exception as error:

                    print(f"Error in executing query - {query}, Error - {error}")

# PREPROCESSING

product_data_df = preprocessing(product_data_df, ['Product Name', 'Description'])

# CATEGORY - FOOD RELATIONSHIP

query_list = create_category_food_relationship_query(product_data_df)

execute_bulk_query(query_list)

    通过使用 match 查询来匹配已经创建的节点,我们在它们之间建立关系。

 

可视化创建的节点

鼠标悬停在

open图标上,然后单击neo4j浏览器以可视化我们创建的节点。
将数据加载到 Neo4j 中

将数据加载到 Neo4j 中

将数据加载到 Neo4j 中

我们的数据连同它们的嵌入一起加载到 neo4j 中。

 

在接下来的博客中,我们将看到如何使用 python 构建图形查询引擎并使用获取的数据进行增强生成。

希望这有帮助…再见!

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

免责声明
1. 本站所有资源来源于用户上传和网络等,如有侵权请邮件联系本站整改team@lcwl.fun!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系本站工作人员处理!
6. 本站资源售价或VIP只是赞助,收取费用仅维持本站的日常运营所需!
7. 如遇到加密压缩包,请使用WINRAR解压,如遇到无法解压的请联系管理员!
8. 因人力时间成本问题,部分源码未能详细测试(解密),不能分辨部分源码是病毒还是误报,所以没有进行任何修改,大家使用前请进行甄别!
9.本站所有源码资源都是经过本站工作人员人工亲测可搭建的,保证每个源码都可以正常搭建,但不保证源码内功能都完全可用,源码属于可复制的产品,无任何理由退款!

网站搭建学习网 Python 将数据加载到 Neo4j 中 https://www.xuezuoweb.com/14165.html

常见问题
  • 本站所有的源码都是经过平台人工部署搭建测试过可用的
查看详情
  • 购买源码资源时购买了带主机的套餐是指可以享受源码和所选套餐型号的主机两个产品,在本站套餐里开通主机可享优惠,最高免费使用主机
查看详情

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务

Fa快捷助手
手机编程软件开发

在手机上用手点一点就能轻松做软件

去做软件
链未云主机
免备案香港云主机

开通主机就送域名的免备案香港云主机

去使用
链未云服务器
免备案香港云服务器

支持售后、超低价、稳定的免备案香港云服务器

去使用