Neo4j 벡터 인덱스 통합
Neo4j 벡터 인덱스 통합 (Neo4j vector index integration)
LangChain JavaScript로 Neo4j 벡터 인덱스 벡터 스토어와 통합해요.
Neo4j는 벡터 유사도 검색이 통합 지원되는 오픈소스 그래프 데이터베이스예요. 근사 최근접 이웃(approximate nearest neighbor) 검색, 유클리드·코사인 유사도, 벡터·키워드 검색을 결합한 하이브리드 검색을 지원해요.
이 가이드는 Neo4j 벡터 스토어 시작을 도와드려요. 모든 Neo4jVectorStore 기능과 구성에 대한 자세한 문서는 API reference를 참고하세요.
개요 (Overview)
통합 세부 정보 (Integration details)
| 클래스 | 패키지 | PY 지원 | Downloads | Version |
|---|---|---|---|---|
Neo4jVectorStore |
@langchain/neo4j |
✅ |
설정 (Setup)
@langchain/neo4j, MongoDB 호환 neo4j-driver, @langchain/core, 그리고 임베딩 제공자(이 가이드는 OpenAI 임베딩 사용)를 설치하세요:
yarn add @langchain/neo4j @langchain/core neo4j-driver @langchain/openai
pnpm add @langchain/neo4j @langchain/core neo4j-driver @langchain/openai
docker-compose로 셀프 호스팅 Neo4j 인스턴스 설정
Neo4j는 셀프 호스팅 Neo4j 데이터베이스 인스턴스를 빠르게 설정할 수 있는 사전 빌드된 Docker 이미지를 제공해요. 아래 docker-compose.yml 파일을 만드세요:
services:
database:
image: neo4j
ports:
- 7687:7687
- 7474:7474
environment:
- NEO4J_AUTH=neo4j/pleaseletmein
그런 다음 같은 디렉터리에서 docker compose up을 실행해 컨테이너를 시작하세요.
Neo4j 설정에 대한 자세한 내용은 웹사이트에서 찾을 수 있어요.
사용법 (Usage)
import { OpenAIEmbeddings } from "@langchain/openai";
import { Neo4jVectorStore } from "@langchain/neo4j";
// Configuration object for Neo4j connection and other related settings
const config = {
url: "bolt://localhost:7687", // URL for the Neo4j instance
username: "neo4j", // Username for Neo4j authentication
password: "pleaseletmein", // Password for Neo4j authentication
indexName: "vector", // Name of the vector index
keywordIndexName: "keyword", // Name of the keyword index if using hybrid search
searchType: "vector" as const, // Type of search (e.g., vector, hybrid)
nodeLabel: "Chunk", // Label for the nodes in the graph
textNodeProperty: "text", // Property of the node containing text
embeddingNodeProperty: "embedding", // Property of the node containing embedding
};
const documents = [
{ pageContent: "what's this", metadata: { a: 2 } },
{ pageContent: "Cat drinks milk", metadata: { a: 1 } },
];
const neo4jVectorIndex = await Neo4jVectorStore.fromDocuments(
documents,
new OpenAIEmbeddings(),
config
);
const results = await neo4jVectorIndex.similaritySearch("water", 1);
console.log(results);
/*
[ Document { pageContent: 'Cat drinks milk', metadata: { a: 1 } } ]
*/
await neo4jVectorIndex.close();
retrievalQuery 파라미터로 응답 커스터마이징 (Use retrievalQuery parameter to customize responses)
import { OpenAIEmbeddings } from "@langchain/openai";
import { Neo4jVectorStore } from "@langchain/neo4j";
/*
* The retrievalQuery is a customizable Cypher query fragment used in the Neo4jVectorStore class to define how
* search results should be retrieved and presented from the Neo4j database. It allows developers to specify
* the format and structure of the data returned after a similarity search.
* Mandatory columns for `retrievalQuery`:
*
* 1. text:
* - Description: Represents the textual content of the node.
* - Type: String
*
* 2. score:
* - Description: Represents the similarity score of the node in relation to the search query. A
* higher score indicates a closer match.
* - Type: Float (ranging between 0 and 1, where 1 is a perfect match)
*
* 3. metadata:
* - Description: Contains additional properties and information about the node. This can include
* any other attributes of the node that might be relevant to the application.
* - Type: Object (key-value pairs)
* - Example: { "id": "12345", "category": "Books", "author": "John Doe" }
*
* Note: While you can customize the `retrievalQuery` to fetch additional columns or perform
* transformations, never omit the mandatory columns. The names of these columns (`text`, `score`,
* and `metadata`) should remain consistent. Renaming them might lead to errors or unexpected behavior.
*/
// Configuration object for Neo4j connection and other related settings
const config = {
url: "bolt://localhost:7687", // URL for the Neo4j instance
username: "neo4j", // Username for Neo4j authentication
password: "pleaseletmein", // Password for Neo4j authentication
retrievalQuery: `
RETURN node.text AS text, score, {a: node.a * 2} AS metadata
`,
};
const documents = [
{ pageContent: "what's this", metadata: { a: 2 } },
{ pageContent: "Cat drinks milk", metadata: { a: 1 } },
];
const neo4jVectorIndex = await Neo4jVectorStore.fromDocuments(
documents,
new OpenAIEmbeddings(),
config
);
const results = await neo4jVectorIndex.similaritySearch("water", 1);
console.log(results);
/*
[ Document { pageContent: 'Cat drinks milk', metadata: { a: 2 } } ]
*/
await neo4jVectorIndex.close();
기존 그래프에서 Neo4jVectorStore 인스턴스화 (Instantiate Neo4jVectorStore from existing graph)
import { OpenAIEmbeddings } from "@langchain/openai";
import { Neo4jVectorStore } from "@langchain/neo4j";
// Configuration object for Neo4j connection and other related settings
const config = {
url: "bolt://localhost:7687", // URL for the Neo4j instance
username: "neo4j", // Username for Neo4j authentication
password: "pleaseletmein", // Password for Neo4j authentication
indexName: "wikipedia",
nodeLabel: "Wikipedia",
textNodeProperties: ["title", "description"],
embeddingNodeProperty: "embedding",
searchType: "hybrid" as const,
};
// You should have a populated Neo4j database to use this method
const neo4jVectorIndex = await Neo4jVectorStore.fromExistingGraph(
new OpenAIEmbeddings(),
config
);
await neo4jVectorIndex.close();
fromExistingGraph 메서드는 Neo4j 데이터베이스의 기존 그래프를 사용해 Neo4jVectorStore 인스턴스를 초기화해요. 텍스트 속성은 있지만 임베딩이 없는 노드에 대해 임베딩을 계산·저장하며, 원본 데이터 구조를 바꾸지 않아요.
메타데이터 필터링 (Metadata filtering)
import { OpenAIEmbeddings } from "@langchain/openai";
import { Neo4jVectorStore } from "@langchain/neo4j";
// Configuration object for Neo4j connection and other related settings
const config = {
url: "bolt://localhost:7687", // URL for the Neo4j instance
username: "neo4j", // Username for Neo4j authentication
password: "pleaseletmein", // Password for Neo4j authentication
indexName: "vector", // Name of the vector index
keywordIndexName: "keyword", // Name of the keyword index if using hybrid search
searchType: "vector" as const, // Type of search (e.g., vector, hybrid)
nodeLabel: "Chunk", // Label for the nodes in the graph
textNodeProperty: "text", // Property of the node containing text
embeddingNodeProperty: "embedding", // Property of the node containing embedding
};
const documents = [
{ pageContent: "what's this", metadata: { a: 2 } },
{ pageContent: "Cat drinks milk", metadata: { a: 1 } },
];
const neo4jVectorIndex = await Neo4jVectorStore.fromDocuments(
documents,
new OpenAIEmbeddings(),
config
);
const filter = { a: { $eq: 1 } };
const results = await neo4jVectorIndex.similaritySearch("water", 1, { filter });
console.log(results);
/*
[ Document { pageContent: 'Cat drinks milk', metadata: { a: 1 } } ]
*/
await neo4jVectorIndex.close();
similaritySearch의 세 번째 파라미터인 filter는 유사도 검색 전에 노드를 사전 필터링하는 메타데이터 기반 조건을 지정해요. 메타데이터 필터링은 $eq, $ne, $lt, $lte, $gt, $gte, $in, $nin, $between, $like, $ilike 연산자와 $and·$or 같은 논리 연산자를 지원해요.
보안 (Security)
데이터베이스 연결이 필요한 권한만 포함하도록 좁게 범위가 지정된 자격 증명을 사용하는지 확인하세요. 그렇지 않으면 호출 코드가 적절히 프롬프트될 때 삭제·데이터 변형을 초래하거나, 데이터베이스에 민감한 데이터가 있다면 이를 읽는 명령을 시도할 수 있어 데이터 손상·손실이 발생할 수 있어요. 이런 부정적인 결과를 막는 가장 좋은 방법은 이 툴에 사용되는 자격 증명에 부여된 권한을 (적절히) 제한하는 거예요. 예를 들어 데이터베이스에 읽기 전용 사용자를 만드는 것은 호출 코드가 데이터를 변형·삭제할 수 없게 하는 좋은 방법이에요.
API reference
모든 Neo4jVectorStore 기능과 구성에 대한 자세한 문서는 API reference를 참고하세요.
관련 (Related)
- 벡터 스토어 개념 가이드
- 벡터 스토어 how-to 가이드
출처: 문서
본문
Neo4jVectorStore는 벡터 유사도 검색이 통합된 오픈소스 그래프 DB인 Neo4j용 통합이에요. @langchain/neo4j 패키지에서 Neo4jVectorStore.fromDocuments로 문서를 인덱싱하고, retrievalQuery로 응답 커스터마이징, fromExistingGraph로 기존 그래프 활용, 메타데이터 필터($eq·$in·$and 등)를 지원해요. searchType으로 vector·hybrid 검색을 선택할 수 있어요. 보안을 위해 연결 자격 증명의 권한을 최소화하세요.