AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。
Docs Menu

MongoDBと Lgachein で親ドキュメント取得を実行

MongoDB ベクトル検索 をLgChuin と統合して、親ドキュメント検索を実行できます。このチュートリアルでは、次の手順を実行します。

  1. 環境を設定します。

  2. データを準備してください。

  3. 親ドキュメントリトリーバーをインスタンス化します。

  4. MongoDB ベクトル検索インデックスを作成します。

  5. RAG パイプラインでレトリーバーを使用します。

親ドキュメントの取得は、大きなドキュメントを小さなチャンクに分割する取得手法です。この手法では、完全な親ドキュメントを LLM に返す前に、小さなチャンクをクエリします。これにより、LLM に親文書の完全なコンテキストを提供しながら、より小さなチャンクでより詳細な検索が可能になるため、RAG エージェントとアプリケーションの応答を向上させることができます。

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

Atlas の サンプル データ セット からの映画データを含むコレクションを使用します。

  • 次のいずれかのMongoDBクラスター タイプ

    • An Atlas cluster running MongoDB version 6.0.11, 7.0.2, or later. Ensure that your IP address is included in your Atlas project's access list.

    • A local Atlas deployment created using Python and Docker. Install atlas-local-lib-py (pip install atlas-local-lib-py) to programmatically create and manage local deployments. To learn more, see the atlas-local-lib-py repository.

    • A MongoDB Community cluster with Search and Vector Search installed.

  • A Voyage AI API key. To create an API key, see Manage Voyage AI Model API Keys.

  • OpenAI APIキー。API リクエストに使用できるクレジットがある OpenAI アカウントが必要です。OpenAI のアカウント登録の詳細については、OpenAI API のウェブサイトをご覧ください。

  • Comb などのインタラクティブ Python ノートを実行するための環境。

このチュートリアルの環境を設定します。 .ipynb 拡張機能のファイルを保存して、インタラクティブPythonノートを作成します。 このノートはPythonコード スニペットを個別に実行でき、このチュートリアルのコードを実行するために使用します。

ノートク環境を設定するには、次の手順に従います。

1

次のコマンドを実行します:

pip install --quiet --upgrade langchain langchain-community langchain-core langchain-mongodb langchain-voyageai langchain-openai pymongo pypdf
2

次のコードを実行し、プレースホルダーを次の値に置き換えます。

  • 投票AIと OpenAI APIキー

  • MongoDBクラスターの接続文字列。

import os
os.environ["VOYAGE_API_KEY"] = "<voyage-api-key>"
os.environ["OPENAI_API_KEY"] = "<openai-api-key>"
MONGODB_URI = "<connection-string>"

注意

<connection-string> を Atlas クラスターまたはローカル Atlas 配置の接続文字列に置き換えます。

接続stringには、次の形式を使用する必要があります。

mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net

詳細については、クライアント ライブラリを使用したクラスターへの接続 を参照してください。

接続stringには、次の形式を使用する必要があります。

mongodb://localhost:<port-number>/?directConnection=true

接続文字列」を参照してください。

ノートブックに次のコードを貼り付けて実行し、最新の MongoDB の収益レポートを含むサンプル PDF を読み込み、チャンクします。

このコードは、テキストスプリッターを使用して、PDFデータを小さな親ドキュメントに分割します。各ドキュメントのチャンクサイズ(文字数)とチャンクオーバーラップ(連続するチャンク間で重なる文字数)を指定します。

from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_community.document_loaders import PyPDFLoader
# Load the PDF
loader = PyPDFLoader("https://investors.mongodb.com/node/12881/pdf")
data = loader.load()
# Chunk into parent documents
parent_splitter = RecursiveCharacterTextSplitter(chunk_size=2000, chunk_overlap=20)
docs = parent_splitter.split_documents(data)
# Print a document
docs[0]

このセクションでは、親ドキュメントレプリカをインスタンス化し、それを使用してMongoDBにデータを取り込みます。

MongoDBAtlasParentDocumentRetriever は、親ドキュメントをより小さな子ドキュメントにチャンク化し、子ドキュメントを埋め込み、親ドキュメントと子ドキュメントの両方をMongoDBの同じコレクションに取り込みます。この検索ドライバーは、次のものを作成します。

  • 子ドキュメントへのベクトル検索クエリを処理するベクトル ストアである MongoDBAtlasVectorSearch のインスタンス。

  • 親ドキュメントの保存と取得を処理するドキュメント ストアである MongoDBDocStore のインスタンス。

1

MongoDBAtlasParentDocumentRetriever を構成する最も速い方法は、from_connection_string メソッドを使用することです。このコードは、次のパラメーターを指定します。

  • connection_string: クラスターに接続するための Atlas 接続文字列。

  • child_splitter: 親ドキュメントを小さな子ドキュメントに分割するために使用するテキストスプリッター。

  • embedding_model: 子ドキュメントを埋め込むために使用する埋め込みモデル。

  • database_name および collection_name: ドキュメントを取り込むためのデータベースおよびコレクション名。

  • MongoDBAtlasVectorSearch ベクトルストアを構成するための、次の任意のパラメーター。

    • text_key: 埋め込むテキストを含むドキュメント内のフィールド

    • relevance_score: ベクトル検索クエリに使用する関連性スコア

    • search_kwargs: 最初の検索で取得する子ドキュメントの数

from langchain_mongodb.retrievers import MongoDBAtlasParentDocumentRetriever
from langchain_voyageai import VoyageAIEmbeddings
# Define the embedding model to use
embedding_model = VoyageAIEmbeddings(model="voyage-3-large")
# Define the chunking method for the child documents
child_splitter = RecursiveCharacterTextSplitter(chunk_size=200, chunk_overlap=20)
# Specify the database and collection name
database_name = "langchain_db"
collection_name = "parent_document"
# Create the parent document retriever
parent_doc_retriever = MongoDBAtlasParentDocumentRetriever.from_connection_string(
connection_string = MONGODB_URI,
child_splitter = child_splitter,
embedding_model = embedding_model,
database_name = database_name,
collection_name = collection_name,
text_key = "page_content",
relevance_score_fn = "dotProduct",
search_kwargs = { "k": 10 },
)
2

次に、レトリーバーの add_documents メソッドを使用して、次のコードを実行し、ドキュメントを Atlas に取り込みます。親ドキュメントを入力として受け取り、レトリーバーの設定に基づいて親ドキュメントと子ドキュメントの両方を取り込みます。

parent_doc_retriever.add_documents(docs)
3

サンプルコードを実行した後、クラスターの langchain_db.parent_document コレクションに移動すると、Atlas UI でドキュメントを表示できます。

親ドキュメントと子ドキュメントの両方に page_content フィールドがあり、チャンクされたテキストが入っています。子ドキュメントには、チャンクされたテキストのベクトル埋め込みが入った追加の embedding フィールドと、親ドキュメントの _id に対応する doc_id フィールドがあります。

Atlas UI で次のクエリを実行し、<id> プレースホルダーを有効なドキュメント ID に置き換えます。

  • 同じ親ドキュメントIDを共有する子ドキュメントを表示するには、次のように行います。

    { doc_id: "<id>" }
  • それらの子ドキュメントの親ドキュメントを表示するには、以下の手順に従ってください。

    { _id: "<id>" }

langchain_db.parent_documentコレクションでベクトル検索クエリを有効にするには、 MongoDB ベクトル検索インデックスを作成する必要があります。LgChuinヘルパーメソッドまたはPyMongoドライバー メソッドのいずれかを使用できます。希望するメソッドとして、ノート PC で次のコードを実行します。

# Get the vector store instance from the retriever
vector_store = parent_doc_retriever.vectorstore
# Use helper method to create the vector search index
vector_store.create_vector_search_index(
dimensions = 1024 # The number of dimensions to index
)
from pymongo import MongoClient
from pymongo.operations import SearchIndexModel
# Connect to your cluster
client = MongoClient(MONGODB_URI)
collection = client[database_name][collection_name]
# Create your vector search index model, then create the index
vector_index_model = SearchIndexModel(
definition={
"fields": [
{
"type": "vector",
"path": "embedding",
"numDimensions": 1024,
"similarity": "dotProduct"
}
]
},
name="vector_index",
type="vectorSearch"
)
collection.create_search_index(model=vector_index_model)

The index should take about one minute to build. While it builds, the index is in an initial sync state. When it finishes building, you can start querying the data in your collection.

MongoDB がインデックスを構築したら、データに対してベクトル検索クエリを実行し、 RGパイプラインでリリーバーを使用できるようになります。 親ドキュメントに次のコードを貼り付けて実行し、親ドキュメント検索を実行するサンプルRAGパイプラインを実装します。

1

特定のクエリに最も関連性の高いドキュメントを表示するには、次のコードを貼り付けて実行し、コレクションでサンプルベクトル検索クエリを実行します。レトリーバーは、文字列 AI technology に意味的に類似した関連する子ドキュメントを検索し、その子ドキュメントに対応する親ドキュメントを返します。

parent_doc_retriever.invoke("AI technology")

LangChain を使用したベクトル検索クエリの例について詳しくは、「ベクトル検索クエリの実行」を参照してください。

2

親ドキュメントのレトリーバーを使用してRAGパイプラインを作成し実行するには、次のコードを貼り付けて実行してください。このコードは、次の処理を行います。

from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import PromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_openai import ChatOpenAI
# Define a prompt template
template = """
Use the following pieces of context to answer the question at the end.
{context}
Question: {query}?
"""
prompt = PromptTemplate.from_template(template)
model = ChatOpenAI()
# Construct a chain to answer questions on your data
chain = (
{"context": parent_doc_retriever, "query": RunnablePassthrough()}
| prompt
| model
| StrOutputParser()
)
# Prompt the chain
query = "In a list, what are MongoDB's latest AI announcements?"
answer = chain.invoke(query)
print(answer)
1. MongoDB obtained the AWS Modernization Competency designation.
2. MongoDB launched a MongoDB University course focused on building AI applications with MongoDB and AWS.
3. MongoDB announced new technology integrations for AI, data analytics, and automating database deployments across various environments.
4. MongoDB launched the MongoDB AI Applications Program (MAAP) to help companies harness the power of data and future AI technologies.
5. Capgemini, Confluent, IBM, Unstructured, and QuantumBlack joined the MAAP ecosystem to offer customers additional integration and solution options.

こちらのビデオでは、 LgDB とMongoDBを使用した親ドキュメントの取得について説明しています。

所要時間: 27分