def create_knowledge_graph(df): # Create unique constraints try: # For Neo4j 5.x and later graph.run("CREATE CONSTRAINT product_id IF NOT EXISTS FOR (p:Product) REQUIRE p.uniq_id IS UNIQUE") graph.run("CREATE CONSTRAINT manufacturer_name IF NOT EXISTS FOR (m:Manufacturer) REQUIRE m.name IS UNIQUE") graph.run("CREATE CONSTRAINT category_name IF NOT EXISTS FOR (c:Category) REQUIRE c.name IS UNIQUE") except Exception as e: # For Neo4j 4.x try: graph.run("CREATE CONSTRAINT ON (p:Product) ASSERT p.uniq_id IS UNIQUE") graph.run("CREATE CONSTRAINT ON (m:Manufacturer) ASSERT m.name IS UNIQUE") graph.run("CREATE CONSTRAINT ON (c:Category) ASSERT c.name IS UNIQUE") except Exception as e: print(f"Warning: Could not create constraints: {e}") for _, row in df.iterrows(): # Create Product node product = Node( "Product", uniq_id=row['uniq_id'], name=row['product_name'], description=row['product_description'], price=float(row['price_value']), currency=row['currency'], review_rating=float(row['average_review_rating']), review_count=int(row['number_of_reviews']), stock_type=row['stock_type'] if pd.notna(row['stock_type']) else None, description_complete=row['description_complete'] ) # Create Manufacturer node manufacturer = Node("Manufacturer", name=row['manufacturer']) # Create Category nodes from hierarchy categories = row['amazon_category_and_sub_category'].split(' > ') previous_category = None for cat in categories: category = Node("Category", name=cat.strip()) graph.merge(category, "Category", "name") if previous_category: # Create hierarchical relationship between categories rel = Relationship(previous_category, "HAS_SUBCATEGORY", category) graph.merge(rel) previous_category = category # Merge nodes and create relationships graph.merge(product, "Product", "uniq_id") graph.merge(manufacturer, "Manufacturer", "name") # Connect product to manufacturer graph.merge(Relationship(product, "MANUFACTURED_BY", manufacturer)) # Connect product to lowest-level category graph.merge(Relationship(product, "BELONGS_TO", previous_category)) # Create the knowledge graph create_knowledge_graph(df)