Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/
Atlas
/ /

MongoDBと Lgachein の統合

Atlas Vector Search を LangChain と統合して、生成系 AI と RAG アプリケーションを構築できます。このページでは、LangChain MongoDB Python 統合と、アプリケーションで使用できるさまざまなコンポーネントの概要を説明します。

はじめる

注意

コンポーネントとメソッドの完全なリストについては、 API参照 を参照してください。

JavaScript 統合については、「LangChain JS/TS」を参照してください。

LangChain で Atlas Vector Search を使用するには、まず langchain-mongodb パッケージをインストールする必要があります。

pip install langchain-mongodb

MongoDBAtlasVectorSearch は、 MongoDBのコレクションからベクトル埋め込みを保存および検索できるベクトルストアです。このコンポーネントを使用してデータの埋め込みを保存し、 Atlas ベクトル検索を使用して埋め込みを検索できます。

このコンポーネントには Atlas Vector Search インデックスが必要です。

ベクトルストアをインスタンス化する最も簡単な方法は、 MongoDBクラスターまたはローカル配置の接続文字列を使用することです。

from langchain_mongodb.vectorstores import MongoDBAtlasVectorSearch
from langchain_voyageai import VoyageAIEmbeddings
# Instantiate the vector store using your MongoDB connection string
vector_store = MongoDBAtlasVectorSearch.from_connection_string(
connection_string = "<connection-string>", # MongoDB cluster URI
namespace = "<database-name>.<collection-name>", # Database and collection name
embedding = VoyageAIEmbeddings(), # Embedding model to use
index_name = "vector_index", # Name of the vector search index
# Other optional parameters...
)

統合は、ベクトル ストアをインスタンス化する他の方法もサポートしています。

  • MongoDB クライアントの使用:

    from langchain_mongodb.vectorstores import MongoDBAtlasVectorSearch
    from langchain_voyageai import VoyageAIEmbeddings
    from pymongo import MongoClient
    # Connect to your MongoDB cluster
    client = MongoClient("<connection-string>")
    collection = client["<database-name>"]["<collection-name>"]
    # Instantiate the vector store
    vector_store = MongoDBAtlasVectorSearch(
    collection = collection, # Collection to store embeddings
    embedding = VoyageAIEmbeddings(), # Embedding model to use
    index_name = "vector_index" # Name of the vector search index
    # Other optional parameters...
    )
  • 作成したドキュメントから以下の操作を行います。

    from langchain_mongodb.vectorstores import MongoDBAtlasVectorSearch
    from langchain_voyageai import VoyageAIEmbeddings
    from langchain_core.documents import Document
    from pymongo import MongoClient
    # Some documents to embed
    document_1 = Document(page_content="foo", metadata={"baz": "bar"})
    document_2 = Document(page_content="thud", metadata={"bar": "baz"})
    docs = [ document_1, document_2 ]
    # Connect to your MongoDB cluster
    client = MongoClient("<connection-string>")
    collection = client["<database-name>"]["<collection-name>"]
    # Create the vector store from documents
    vector_store = MongoDBAtlasVectorSearch.from_documents(
    documents = docs, # List of documents to embed
    embedding = VoyageAIEmbeddings(), # Embedding model to use
    collection = collection, # Collection to store embeddings
    index_name = "vector_index" # Name of the vector search index
    # Other optional parameters...
    )

LgChuin 検索は、ベクトルストアから関連するドキュメントを取得するために使用するコンポーネントです。 LgChuin に組み込まれている検索ドライバーまたは次のMongoDB検索ドライバーを使用して、 MongoDBからデータをクエリして検索できます。

MongoDB をベクトルストア としてインスタンス化した後、ベクトルストアのインスタンスを 取得 として使用して、 Atlas ベクトル検索でデータをクエリできます。

from langchain_mongodb.vectorstores import MongoDBAtlasVectorSearch
# Instantiate the vector store
vector_store = MongoDBAtlasVectorSearch.from_connection_string(
# Vector store arguments...
)
# Use the vector store as a retriever
retriever = vector_store.as_retriever()
# Define your query
query = "some search query"
# Print results
documents = retriever.invoke(query)
for doc in documents:
print(doc)

MongoDBAtlasFullTextSearchRetriever は、 Atlas Search を使用して全文検索を実行する検索ドライバーです。具体的には、 Lucene の標準 IBM25 アルゴリズムを使用します。

この検索システムには Atlas Search インデックスが必要です。

from langchain_mongodb.retrievers.full_text_search import MongoDBAtlasFullTextSearchRetriever
# Connect to your MongoDB cluster
client = MongoClient("<connection-string>")
collection = client["<database-name>"]["<collection-name>"]
# Initialize the retriever
retriever = MongoDBAtlasFullTextSearchRetriever(
collection = collection, # MongoDB Collection in Atlas
search_field = "<field-name>", # Name of the field to search
search_index_name = "<index-name>" # Name of the search index
)
# Define your query
query = "some search query"
# Print results
documents = retriever.invoke(query)
for doc in documents:
print(doc)

MongoDBAtlasHybridSearchRetriever は、相互ランク融合 (RRF) アルゴリズムを使用してベクトル検索と全文検索の結果を組み合わせた検索システムです。詳しくは、「ハイブリッド検索の実行方法」を参照してください。

この検索システムには、既存のベクトル ストアAtlas Vector Search インデックス、および Atlas Search インデックス が必要です。

from langchain_mongodb.retrievers.hybrid_search import MongoDBAtlasHybridSearchRetriever
# Initialize the retriever
retriever = MongoDBAtlasHybridSearchRetriever(
vectorstore = <vector-store>, # Vector store instance
search_index_name = "<index-name>", # Name of the Atlas Search index
top_k = 5, # Number of documents to return
fulltext_penalty = 60.0, # Penalty for full-text search
vector_penalty = 60.0 # Penalty for vector search
)
# Define your query
query = "some search query"
# Print results
documents = retriever.invoke(query)
for doc in documents:
print(doc)

MongoDBAtlasParentDocumentRetriever は、最初に小さなチャンクをクエリし、その後、大きな親ドキュメントを LLM に返す検索システムです。このタイプの検索システムは、親ドキュメント検索と呼ばれます。親ドキュメント検索により、より小さなチャンクでのより詳細な検索が可能になり、同時に LLM に親ドキュメントの完全なコンテキストが提供されるため、RAG エージェントとアプリケーションの応答が向上します。

このレトリーバーは、親ドキュメントと子ドキュメントの両方を 1 つの MongoDB コレクションに保存できるため、子ドキュメントの埋め込みを計算してインデックスを作成するだけで効率的な検索が可能になります。

内部的には、このレトリーバーは以下を作成します。

  • 子ドキュメントに対するベクトル検索クエリを取り扱う MongoDBAtlasVectorSearch のインスタンス。

  • 親ドキュメントの保存と検索を取り扱う MongoDBDocStore のインスタンス。

from langchain_mongodb.retrievers.parent_document import ParentDocumentRetriever
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_voyageai import VoyageAIEmbeddings
retriever = MongoDBAtlasParentDocumentRetriever.from_connection_string(
connection_string = <connection-string>, # MongoDB cluster URI
embedding_model = VoyageAIEmbeddings(), # Embedding model to use
child_splitter = RecursiveCharacterTextSplitter(), # Text splitter to use
database_name = <database-name>, # Database to store the collection
collection_name = <collection-name>, # Collection to store the collection
# Additional vector store or parent class arguments...
)
# Define your query
query = "some search query"
# Print results
documents = retriever.invoke(query)
for doc in documents:
print(doc)

MongoDBAtlasSelfQueryRetriever は、それ自体をクエリするレプリカです。検索クエリークエリーは LM を使用して処理され、可能なメタデータフィルターを識別し、フィルター付きで構造化ベクトル検索クエリーを作成し、そのクエリを実行して最も関連性の高いドキュメントを検索します。

例、「2010 以降の評価が 8 を超えるアクション映画は何ですか」のようなクエリでは、取得者は genreyearrating フィールドのフィルターを識別し、それらを使用できますクエリに一致するドキュメントを検索するためにフィルタリングします。

この検索インデックスには、既存のベクトルストアAtlas ベクトル検索インデックスが必要です。

from langchain_mongodb.retrievers import MongoDBAtlasSelfQueryRetriever
from langchain_mongodb import MongoDBAtlasVectorSearch
# Given an existing vector store with movies data, define metadata describing the data
metadata_field_info = [
AttributeInfo(
name="genre",
description="The genre of the movie. One of ['science fiction', 'comedy', 'drama', 'thriller', 'romance', 'animated']",
type="string",
),
AttributeInfo(
name="year",
description="The year the movie was released",
type="integer",
),
AttributeInfo(
name="rating", description="A 1-10 rating for the movie", type="float"
),
]
# Create the retriever from the VectorStore, an LLM and info about the documents
retriever = MongoDBAtlasSelfQueryRetriever.from_llm(
llm=llm,
vectorstore=vector_store,
metadata_field_info=metadata_field_info,
document_contents="Descriptions of movies",
enable_limit=True
)
# This example results in the following composite filter sent to $vectorSearch:
# {'filter': {'$and': [{'year': {'$lt': 1960}}, {'rating': {'$gt': 8}}]}}
print(retriever.invoke("Movies made before 1960 that are rated higher than 8"))

GraphRAG は従来の RAG に代わるアプローチで、データをベクトル埋め込みではなく、エンティティとその関係の知識グラフとして構造化します。ベクトルベースの RAG はクエリに対して意味的に類似したドキュメントを見つけますが、GraphRAG はクエリに関連するエンティティを見つけ、グラフ内の関係をたどって関連情報を検索します。

このアプローチは関係がベースとなる質問で特に役立ちます。たとえば、「A 会社と B 会社のつながりは何ですか?」や「X さんのマネージャーは誰ですか?」などの質問です。

MongoDBGraphStore は、LangChain MongoDB 統合内のコンポーネントであり、エンティティ(ノード)とその関係(エッジ)を MongoDB コレクションに保存することで GraphRAG を実装できるようにします。コレクション内の他のドキュメントを参照する関係フィールドのあるドキュメントとして各エンティティを保存し、$graphLookup 集計ステージを使用してクエリを実行します。

from langchain_mongodb import MongoDBGraphStore
from langchain_openai import ChatOpenAI
# Initialize the graph store
graph_store = MongoDBGraphStore(
connection_string = "<connection-string>", # MongoDB cluster URI
database_name = "<database-name>", # Database to store the graph
collection_name = "<collection-name>", # Collection to store the graph
entity_extraction_model = ChatOpenAI(), # LLM to extract entities from documents (e.g. OpenAI model)
# Other optional parameters...
)
# Add documents to the graph
docs = [...] # Your documents
graph_store.add_documents(docs)
# Query the graph
query = "Who is the CEO of MongoDB?"
answer = graph_store.chat_response(query)
print(answer.content)

キャッシュは、同様のクエリまたは反復的なクエリの反復的な応答を保存して、再計算を避けることで、LM のパフォーマンスを最適化するために使用されます。 MongoDB は、Lgachein アプリケーションに対して次のキャッシュを提供します。

MongoDBCache を使用すると、 MongoDBコレクションに基本的なキャッシュを保存できます。

from langchain_mongodb import MongoDBCache
from langchain_core.globals import set_llm_cache
set_llm_cache(MongoDBCache(
connection_string = "<connection-string>", # MongoDB cluster URI
database_name = "<database-name>", # Database to store the cache
collection_name = "<collection-name>" # Collection to store the cache
))

セマンティックキャッシュは、ユーザー入力とキャッシュされた結果のセマンティックな類似性に基づいて、キャッシュされたプロンプトを検索する、より高度なキャッシュ形式です。

MongoDBAtlasSemanticCache は、Atlas Vector Search を使用してキャッシュされたプロンプトを検索する、セマンティックキャッシュです。このコンポーネントには、Atlas Vector Search インデックスが必要です。

from langchain_mongodb import MongoDBAtlasSemanticCache
from langchain_core.globals import set_llm_cache
from langchain_voyageai import VoyageAIEmbeddings
set_llm_cache(MongoDBAtlasSemanticCache(
embedding = VoyageAIEmbeddings(), # Embedding model to use
connection_string = "<connection-string>", # MongoDB cluster URI
database_name = "<database-name>", # Database to store the cache
collection_name = "<collection-name>" # Collection to store the cache
))

MongoDB Agent Tools は、LingGraph ReAct Agent に渡すと、 MongoDBリソースを操作できるようにするツールのコレクションです。

名前
説明

MongoDBDatabaseToolkit

MongoDBデータベース をクエリするためのツール。

InfoMongoDBDatabaseTool

MongoDBデータベースに関するメタデータを取得するためのツール。

ListMongoDBDatabaseTool

MongoDB database のコレクション名を取得するためのツール。

QueryMongoDBCheckerTool

LM を呼び出してデータベースクエリが正しいかどうかを確認するツール。

from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent
from langchain_mongodb.agent_toolkit import (
MONGODB_AGENT_SYSTEM_PROMPT,
MongoDBDatabase,
MongoDBDatabaseToolkit,
)
db_wrapper = MongoDBDatabase.from_connection_string(
CONNECTION_STRING, database=DB_NAME
)
llm = ChatOpenAI(model="gpt-4o-mini", timeout=60)
toolkit = MongoDBDatabaseToolkit(db=db_wrapper, llm=llm)
system_message = MONGODB_AGENT_SYSTEM_PROMPT.format(top_k=5)
test_query = "Which country's customers spent the most?"
agent = create_react_agent(llm, toolkit.get_tools(), state_modifier=system_message)
agent.step_timeout = 60
events = agent.stream(
{"messages": [("user", test_query)]},
stream_mode="values",
)
messages = []

ドキュメントローダーは LangChain アプリケーションにデータをロードするのに役立つツールです。

MongoDBLoader は、MongoDB データベースからドキュメントのリストを返すドキュメントローダーです。

from langchain_mongodb.loaders import MongoDBLoader
loader = MongoDBLoader.from_connection_string(
connection_string = "<connection-string>", # MongoDB cluster URI
db_name = "<database-name>", # Database that contains the collection
collection_name = "<collection-name>", # Collection to load documents from
filter_criteria = { "field": "value" }, # Optional document to specify a filter
field_names = ["<field-name>", "..." ], # Optional list of fields to include in document content
metadata_names = ["<metadata-field>", "..."] # Optional metadata fields to extract
)
docs = loader.load()

MongoDBChatMessageHistory は、MongoDB データベースにチャット メッセージ履歴を保存および管理できるコンポーネントです。ユーザーと AI が生成したメッセージの両方を、一意のセッション識別子に関連付けて保存することができます。これは、チャットボットなど、時間の経過に伴うインタラクションの追跡が必要なアプリケーションに役立ちます。

from langchain_mongodb.chat_message_histories import MongoDBChatMessageHistory
chat_message_history = MongoDBChatMessageHistory(
session_id = "<session-id>", # Unique session identifier
connection_string = "<connection-string>", # MongoDB cluster URI
database_name = "<database-name>", # Database to store the chat history
collection_name = "<collection-name>" # Collection to store the chat history
)
chat_message_history.add_user_message("Hello")
chat_message_history.add_ai_message("Hi")
chat_message_history.messages
[HumanMessage(content='Hello'), AIMessage(content='Hi')]

MongoDB でデータを管理および保存するために、次のカスタム データ ストアを使用できます。

MongoDBDocStore は、MongoDB を使用してドキュメントを保存および管理するカスタム キーバリュー ストアです。CRUD 操作は、他の MongoDB コレクションと同様に実行できます。

from pymongo import MongoClient
from langchain_mongodb.docstores import MongoDBDocStore
# Replace with your MongoDB connection string and namespace
connection_string = "<connection-string>"
namespace = "<database-name>.<collection-name>"
# Initialize the MongoDBDocStore
docstore = MongoDBDocStore.from_connection_string(connection_string, namespace)

MongoDBByteStore は、MongoDB を使用してバイナリデータ、具体的にはバイトで表されるデータを保存および管理するカスタム データストアです。キーが文字列で値がバイト シーケンスであるキーと値のペアを使用して、CRUD 操作を実行できます。

from langchain.storage import MongoDBByteStore
# Instantiate the MongoDBByteStore
mongodb_store = MongoDBByteStore(
connection_string = "<connection-string>", # MongoDB cluster URI
db_name = "<database-name>", # Name of the database
collection_name = "<collection-name>" # Name of the collection
)
# Set values for keys
mongodb_store.mset([("key1", b"hello"), ("key2", b"world")])
# Get values for keys
values = mongodb_store.mget(["key1", "key2"])
print(values) # Output: [b'hello', b'world']
# Iterate over keys
for key in mongodb_store.yield_keys():
print(key) # Output: key1, key2
# Delete keys
mongodb_store.mdelete(["key1", "key2"])

Atlas Vector Search を LangGraph と統合する方法については、「MongoDB と LangGraph の統合」を参照してください。

インタラクティブPythonノートについては、 Docs Notes リポジトリ およびジェネレーティブAIが使用するリポジトリ を参照してください。

戻る

AI 統合

ルール バッジを取得する

「MongoDB を使用した RAG」を無料でマスターしましょう!

詳細