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

MongoDBと LgDB でハイブリッド検索の実行

MongoDB を LangChain と統合して hybrid search を実行することができます。このチュートリアルでは、以下の手順を完了します:

  1. 環境を設定します。

  2. MongoDB をベクトルストアとして使用します。

  3. データにMongoDB ベクトル検索とMongoDB Searchインデックスを作成します。

  4. ハイブリッド検索クエリを実行します。

  5. クエリ結果を RGパイプラインに渡します 。

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

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

    • MongoDB バージョン 6.0.11 を実行している Atlas クラスター、7.0.2以降。IP アドレスが Atlas プロジェクトのアクセスリストに含まれていることを確認します。

    • Python と Docker を使用して作成されたローカル Atlas 配置。atlas-local-lib-py (pip install atlas-local-lib-py) をインストールして、ローカル配置をプログラムで作成および管理します。詳細については、atlas-local-lib-py リポジトリを参照してください。

    • 検索とベクトル検索がインストールされた MongoDB Community クラスター。

  • Voyage AI API キー。API キーを作成するには、Voyage AI モデル API キーの管理を参照してください。

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

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

注意

互換性のあるPythonバージョンを使用していることを確認するには、 langgroup-voiceail パッケージの要件を確認してください。

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

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

1

ノートブックで次のコマンドを実行します。

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

このチュートリアルの環境変数を設定するには、次のコードを実行します。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

重要:接続文字列にデータベースユーザーの認証情報が含まれていることを確認します。接続文字列の検索方法の詳細については、クライアント ライブラリ経由でクラスターに接続する を参照してください。

データのベクトルストアとしてMongoDB を使用する必要があります。MongoDBでは既存のコレクションを使用してベクトルストアをインスタンス化できます。

1

まだ行っていない場合は、手順を完了してサンプルデータをクラスターにロードします。

注意

独自のデータを使用する場合は、Atlas に vector embeddings を取り込む方法については、LangChain の使用を開始する、またはvector embeddings を手動で作成する方法を参照してください。

2

次のコードをノート PC に貼り付けて実行し、Atlas の sample_mflix.embedded_movies名前空間から vector_store という名前のベクトルストアインスタンスを作成します。 このコードでは、from_connection_string メソッドを使用して MongoDBAtlasVectorSearchベクトルストアを作成し、次のパラメータを指定します。

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

  • テキストをベクトル埋め込みに変換するための Vyage AIの voyage-3-large 埋め込みモデル。

  • sample_mflix.embedded movies 使用する名前空間として 。

  • plot : テキストを含むフィールド。

  • plot_embedding_voyage_3_large 埋め込みを含むフィールドとして。

  • dotProduct 関連性スコア関数として。

from langchain_mongodb import MongoDBAtlasVectorSearchfrom langchain_voyageai import VoyageAIEmbeddings # Create the vector storevector_store = MongoDBAtlasVectorSearch.from_connection_string( connection_string = MONGODB_URI, embedding = VoyageAIEmbeddings(model = "voyage-3-large", output_dimension = 2048), namespace = "sample_mflix.embedded_movies", text_key = "plot", embedding_key = "plot_embedding_voyage_3_large", relevance_score_fn = "dotProduct")

ベクトルストアでハイブリッド検索クエリを有効にするには、コレクションにMongoDB ベクトル検索とMongoDB Searchインデックスを作成します。インデックスは、LgChuinヘルパーメソッドまたはPyMongoドライバー メソッドのいずれかを使用して作成できます。

1

次のコードを実行して、コレクションの plot_embedding_voyage_3_largeフィールドにインデックスを付けるベクトル検索インデックスを作成します。

# Use helper method to create the vector search indexvector_store.create_vector_search_index( dimensions = 2048 # The dimensions of the vector embeddings to be indexed)
2

ノートブックで次のコードを実行して、コレクションの plot フィールドにインデックスを付ける検索インデックスを作成します。

from langchain_mongodb.index import create_fulltext_search_indexfrom pymongo import MongoClient # Connect to your clusterclient = MongoClient(MONGODB_URI) # Use helper method to create the search indexcreate_fulltext_search_index( collection = client["sample_mflix"]["embedded_movies"], field = "plot", index_name = "search_index")

Tip

create_fulltext_search_index API リファレンス

インデックスの構築には 1 分ほどかかります。ビルドする間、インデックスは最初の同期状態にあります。作成が完了したら、コレクション内のデータのクエリを開始できます。

MongoDBによってインデックスが構築されたら、データに対してハイブリッド検索クエリを実行できます。次のコードでは、MongoDBAtlasHybridSearchRetriever リトリバー を使用して string "time travel" のハイブリッド検索を実行します。また、次のパラメータも指定します。

  • vectorstore:ベクトルストアインスタンスの名前。

  • search_index_name: MongoDB Searchインデックスの名前。

  • top_k: 返されるドキュメントの数。

  • fulltext_penalty: 全文検索のペナルティ。

    ペナルティが低いほど、全文検索スコアが高くなります。

  • vector_penalty:ベクトル検索のペナルティ。

    ペナルティが低いほどベクトル検索スコアが高くなります。

レプリカは、全文検索スコアとベクトル検索スコアの合計でソートされたドキュメントのリストを返します。 コード例の最終出力には、タイトル、プロット、および 各ドキュメントの異なるスコアが含まれます。

ハイブリッド検索クエリー結果の詳細については、「 クエリについて 」を参照してください。

from langchain_mongodb.retrievers.hybrid_search import MongoDBAtlasHybridSearchRetriever # Initialize the retrieverretriever = MongoDBAtlasHybridSearchRetriever( vectorstore = vector_store, search_index_name = "search_index", top_k = 5, fulltext_penalty = 50, vector_penalty = 50, post_filter=[ { "$project": { "plot_embedding": 0, "plot_embedding_voyage_3_large": 0 } } ]) # Define your queryquery = "time travel" # Print resultsdocuments = retriever.invoke(query)for doc in documents: print("Title: " + doc.metadata["title"]) print("Plot: " + doc.page_content) print("Search score: {}".format(doc.metadata["fulltext_score"])) print("Vector Search score: {}".format(doc.metadata["vector_score"])) print("Total score: {}\n".format(doc.metadata["fulltext_score"] + doc.metadata["vector_score"]))
Title: TimecopPlot: An officer for a security agency that regulates time travel, must fend for his life against a shady politician who has a tie to his past.Search score: 0.019230769230769232Vector Search score: 0.018518518518518517Total score: 0.03774928774928775 Title: A.P.E.X.Plot: A time-travel experiment in which a robot probe is sent from the year 2073 to the year 1973 goes terribly wrong thrusting one of the project scientists, a man named Nicholas Sinclair into a...Search score: 0.018518518518518517Vector Search score: 0.018867924528301886Total score: 0.0373864430468204 Title: About TimePlot: At the age of 21, Tim discovers he can travel in time and change what happens and has happened in his own life. His decision to make his world a better place by getting a girlfriend turns out not to be as easy as you might think.Search score: 0Vector Search score: 0.0196078431372549Total score: 0.0196078431372549 Title: The Time Traveler's WifePlot: A romantic drama about a Chicago librarian with a gene that causes him to involuntarily time travel, and the complications it creates for his marriage.Search score: 0.0196078431372549Vector Search score: 0Total score: 0.0196078431372549 Title: RetroactivePlot: A psychiatrist makes multiple trips through time to save a woman that was murdered by her brutal husband.Search score: 0Vector Search score: 0.019230769230769232Total score: 0.019230769230769232

ハイブリッド検索結果を CRGパイプラインに渡して、検索されたドキュメントに対して応答を生成できます。サンプルコードでは、次の処理が行われます。

from langchain_core.output_parsers import StrOutputParserfrom langchain_core.prompts import PromptTemplatefrom langchain_core.runnables import RunnablePassthroughfrom langchain_openai import ChatOpenAI # Define a prompt templatetemplate = """ Use the following pieces of context to answer the question at the end. {context} Question: Can you recommend some movies about {query}?"""prompt = PromptTemplate.from_template(template)model = ChatOpenAI() # Construct a chain to answer questions on your datachain = ( {"context": retriever, "query": RunnablePassthrough()} | prompt | model | StrOutputParser()) # Prompt the chainquery = "time travel"answer = chain.invoke(query)print(answer)
Certainly! Here are some movies about time travel from the context provided: 1. **Timecop (1994)** Genre: Action, Crime, Sci-Fi Plot: A law enforcement officer working for the Time Enforcement Commission battles a shady politician with a personal tie to his past. IMDb Rating: 5.8 2. **A.P.E.X. (1994)** Genre: Action, Sci-Fi Plot: A time-travel experiment gone wrong thrusts a scientist into an alternate timeline plagued by killer robots. IMDb Rating: 4.3 3. **About Time (2013)** Genre: Drama, Fantasy, Romance Plot: A young man discovers he can time travel and uses this ability to improve his life, especially his love life, but learns the limitations and challenges of his gift. IMDb Rating: 7.8 4. **The Time Traveler's Wife (2009)** Genre: Drama, Fantasy, Romance Plot: A Chicago librarian with a gene causing him to involuntarily time travel struggles with its impact on his romantic relationship and marriage. IMDb Rating: 7.1 5. **Retroactive (1997)** Genre: Action, Crime, Drama Plot: A woman accidentally time-travels to prevent a violent event, but her attempts to fix the situation lead to worsening consequences due to repeated time cycles. IMDb Rating: 6.3 Each movie covers time travel with unique perspectives, from action-packed adventures to romantic dramas.

ドキュメンテーション