Bering Note – formerly 流沙河鎮

情報技術系のこと書きます。

ローカル環境でOpenSearchの様々な検索アプローチを手早く試す: opensearch-ml-quickstartの紹介

opensearch-ml-quickstartとは


OpenSearchはスケーラブルで多機能なオープンソース検索エンジンです。
その用途は多岐に渡り、近年では従来のキーワードマッチングに加えて、意味を理解するセマンティック検索や、自然な会話で情報を引き出す対話型AIといったアプローチにも注目が集まっています。
しかしながら、こうした技術を実際に試そうとすると、しばしば環境構築や設定の複雑さに阻まれて時間がかかってしまいがちです。
opensearch-ml-quickstartは、こうした障壁を取り除くために設計されたPythonベースのツールキットです。OpenSearchが持つ強力なML機能を、実用的なコード例と抽象化レイヤーを通じて、開発者がすぐに実験できる形で提供します。
Docker ComposeでOpenSearchクラスタを起動し、サンプルデータをロードすれば、すぐに使い始めることができます。
github.com

ローカル環境でのセットアップ

まず、リポジトリをクローンしてPython環境を準備します。

git clone https://github.com/Jon-AtAWS/opensearch-ml-quickstart.git
cd opensearch-ml-quickstart
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

次に、Docker ComposeでOpenSearchクラスタを起動します。
必要なML Commonsプラグインなどは事前設定されているため、追加の設定は不要です。
環境変数OPENSEARCH_INITIAL_ADMIN_PASSWORDにパスワードを設定するのを忘れないでください。

export OPENSEARCH_INITIAL_ADMIN_PASSWORD=<password>
docker compose up

最後に、設定ファイルconfigs/osmlqs.yamlを開き、OPENSEARCH_ADMIN_USEROPENSEARCH_ADMIN_PASSWORDを変更してください。
ユーザー名はadmin、パスワードは先ほど設定したものです。

OPENSEARCH_ADMIN_USER: admin
OPENSEARCH_ADMIN_PASSWORD: <password>

これでOpenSearchの準備は完了です。

データセット

デフォルトで用意されているサンプルは、Amazon Product Question and Answers (PQA)データセットを利用する作りになっています。
これにはAmazonの実際の製品に関する質問と回答が300万件以上含まれており、様々な検索を実験するのに適しています。
各ドキュメントには製品のカテゴリ、説明、Q&Aなどが含まれます。

データセットは以下のコマンドでダウンロードできます。

cd datasets
aws s3 cp --no-sign-request s3://amazon-pqa/amazon-pqa.tar.gz .
mkdir -p amazon_pqa
tar -xzf amazon-pqa.tar.gz -C amazon_pqa

データセットはelectronics、books、technologyなど、複数のカテゴリに分類されています。
これらはサンプルの実行時に--categoriesを指定することで使用するカテゴリを指定できます。
data_processフォルダ内のQandAFileReaderクラスは、このデータを検索に適した形式に変換します。
製品情報とQ&Aを組み合わせて検索可能なテキストチャンクを作成し、埋め込み生成に最適化された構造にします。

ワークロードサンプル

exampleフォルダには、様々な検索アプローチのサンプルが含まれており、それぞれが独立して動作します。

~/opensearch-ml-quickstart/examples main*
.venv ❯ tree
.
├── agent_tools.py
├── cmd_line_interface.py
├── conversational_agent.py
├── conversational_search.py
├── dense_exact_search.py
├── dense_hnsw_search.py
├── dense_vs_lexical.ipynb
├── hybrid_local_search.py
├── hybrid_search.py
├── lexical_search.py
├── semantic_search_workflow.py
├── sparse_search.py
├── workflow_example.py
└── workflow_with_template.py

サンプルによってAmazon OpenSearch Serviceでのみ動くもの(OpenSearch Typeがaos)と、ローカル環境でも動くもの(OpenSearch Typeがos)があります。
OpenSearch Typeがosのサンプルは、embeddingモデル等も含めてローカルで完結して動くため、完全にスタンドアローンな環境での検証が可能です。

Example OpenSearch Type Model Hosting Model Host Model Type
dense_exact_search.py aos remote sagemaker embedding
dense_hnsw_search.py aos remote bedrock embedding
sparse_search.py aos remote sagemaker embedding
hybrid_search.py aos remote sagemaker embedding
hybrid_local_search.py os local n/a embedding
lexical_search.py os/aos n/a n/a n/a
conversational_search.py aos remote sagemaker embedding + llm
conversational_agent.py os local n/a embedding + llm
workflow_example.py aos remote bedrock embedding
workflow_with_template.py aos remote sagemaker embedding

試しにローカルでの全文検索とベクトル検索のハイブリッドクエリを実験するhybrid_local_search.pyを試してみましょう。
ここで、--categories tabletsは対象のデータセットをtablets関連のものに絞り、-n 100はその中の100件のデータを使用することを意味しています。
--opensearch-type osはローカルのOpenSearchを利用することを意味しています。
この辺りは実験の目的や、リソースに合わせて調整すると良いでしょう。

python examples/hybrid_local_search.py \   
  --opensearch-type os \
  --categories "tablets" \
  -n 200

無事に起動に成功すると、インタラクティブなクエリインターフェースが表示されます。

今回検索対象としているkeyboards関連のデータの中身はdatasets/amazon_pqa/amazon_pqa_tablets.jsonを見るとわかります。

{"question_id": "Tx1GYNDQIT5N9PC", "question_text": "Does this tablet have flash player", "asin": "B0045FM6SU", "bullet_point1": "Linux 1 GHz Motorola ARM dual-core CORTEX A9 OMAP 4", "bullet_point2": "1 GB DRAM", "bullet_point3": "Android 3.1 (Honeycomb).", "bullet_point4": "802 11 BGN", "bullet_point5": "It also consists of 802.11b/g/n, 5-megapixel rear-facing camera, 2-megapixel front-facing web cam.", "product_description": "", "brand_name": "Motorola", "item_name": "MOTOROLA XOOM Android Tablet (10.1-Inch, 32GB, Wi-Fi)", "question_type": "yes-no", "answer_aggregated": "no", "answers": [{"answer_text": "No"}, {"answer_text": "How do I download Adobe  Flash  Player? Adobe Flash Player 10.2 or higher is now available as a free download from the Android Market (normal data charges apply).  To download Adobe Flash Player  from the Android market:  From the home screen, touch Apps Tap Market In the search field above, type  Adobe flash player  and select Flash Player 10.2 or higher by Adobe Systems Tap download and install    Note: There are some sites where minor work needs to be completed to take advantage of the updated Flash solution. Daily we're seeing more sites take the steps to make these updates  check regularly to see if your favorites have been updated.  In addition, please note, on many sites, you can find a  \"contact us \" link, and you can let them know you'd like to see their site be fully Flash 10.2 or higher compatible.  Others are probably thinking the same as you.\""}, {"answer_text": "No. But flash can be sideloaded."}, {"answer_text": "I don't have it on mine but believe you can find it under the apps available and then download it"}]}

これを念頭に適当な検索クエリを入れてみましょう。
以下の通り、ハイブリッドクエリが実行されている様子が観察できます。

クエリ実行結果 Search Query: MOTOROLA XOOM Android Tablet Search pipeline config: { "description": "Hybrid search pipeline combining lexical and dense vector results", "phase_results_processors": [ { "normalization-processor": { "normalization": { "technique": "min_max" }, "combination": { "technique": "arithmetic_mean", "parameters": { "weights": [ 0.4, 0.6 ] } } } } ] }

Executing Search Query: Search query: { "size": 5, "query": { "hybrid": { "queries": [ { "match": { "chunk": { "query": "MOTOROLA XOOM Android Tablet", "boost": 1.0 } } }, { "neural": { "chunk_embedding": { "query_text": "MOTOROLA XOOM Android Tablet", "model_id": "QEEkv5kBuKWAiqvPJUPq", "k": 10, "boost": 1.0 } } } ] } }

}

2025-10-08:00:11:54,700 INFO [base.py:258] POST https://localhost:9200/hybrid_local_search/_search?search_pipeline=hybrid-local-search-pipeline [status:200 request:0.257s]

Search Results: Found 100 total matches, showing top 5 results:


Item 1 category: tablets Item 1 product name: MOTOROLA XOOM Android Tablet (10.1-Inch, 32GB, Wi-Fi)

Question: my tablet does not wankth to start.i ca o Answer 1: I only have a suggestion for your situation, please try charging your battery for 8 hours it might be drained. I also know if you have a white light charging, green charged. Please try this hope this helps. Answer 2: Sometimes you have to push the start button and hold it untill ir warms up. Then you will see it start and can release it. Answer 3: You need to reboot your system. Hold down the volume up button and the power button for approximately 3 seconds. Should reboot your entire system Answer 4: it takes awhile for the tablet to boot. hold the start button in for a few seconds to engage it. otherwise i can't help--sorry Answer 5: That happens to mine and I don't know why. I did this which I think worked. Hold up volume and power botton at same time pump power botton. Good luck Answer 6: Others have said that you should hold the power button down and at the same time press and hold the top volume button down till the tablet boots. You didn't give me enough information to tell you too much else. Another possibility is that you might need to press the bottom button down as well. There is the possibility also that you might just accidentally enter into The Recovery Mode ". If this happens, use Recovery Mode to restart your system. These things should give you lots of help, but as I noted before, you didn't give me enough info to really get the help you need. My advice is to go to the Motorola Xoom Forum of XDA, and register yourself there. Restate your question there and look for the Kingsman to answer. I'll be glad to help walk you through the problems. http://forum.xda-developers.com/motorola-xoom/help/page237"


Item 2 category: tablets Item 2 product name: MOTOROLA XOOM Android Tablet (10.1-Inch, 32GB, Wi-Fi)

Question: What is the batery info I need to order replacement? How to find model number? Battery won't hold charge after 5 months of limited use. Answer 1: Here is a youtube video of taking the xoom apart and taking out the battery: https://www.youtube.com/watch?v WZVtlVEY-3E Answer 2: I use my xoom 10 hours or more a day and plug it in to charge overnight. If I forget it does not take but a couple hours to charge during the day. I bought it used and have had problems with chargers but not the battery and have had it over 2 years. Are you sure it is a problem with the battery? Have yo tried a different charger? If you have to buy a battery you might as well buy a used xoom. Here is a link to some on amazon.com at less than $70 including shipping and no sales tax. https://www.amazon.com/gp/offer-listing/B0045FM6SU/ref sr 1 3 olp?ie UTF8&qid 1446348003&sr 8-3&keywords motorola+xoom+battery&condition used A battery with tax and shipping will cost almost that much. https://www.amazon.com/s/ref sr nr n 1?fst as%3Aoff&rh n%3A720576%2Ck%3Amotorola+xoom+battery&keywords motorola+xoom+battery&ie UTF8&qid 1446348003&rnid 2941120011 I really like my xoom. It freezes sometimes and requires the power button and volume up at the same time to reboot. Also it goes crazy if I don't power it off every few days. It is android so there are lots of apps and games at the google play store.


Item 3 category: tablets Item 3 product name: MOTOROLA XOOM Android Tablet (10.1-Inch, 32GB, Wi-Fi)

Question: THIS CHART WORKS IN VENEZUELA? Answer 1: Wifi? Yes.


Item 4 category: tablets Item 4 product name: MOTOROLA XOOM Android Tablet (10.1-Inch, 32GB, Wi-Fi)

Question: Does this come with the charger Answer 1: Yes it does! Answer 2: Yes Answer 3: You're so very welcome. Happy to help. Answer 4: Yes it comes with charger. Answer 5: Yes it does. It comes with everything required to make it work. Answer 6: If it's New it should come with a charger. If you need a charger I have one you can have if you pay postage for mailing


Item 5 category: tablets Item 5 product name: MOTOROLA XOOM Android Tablet (10.1-Inch, 32GB, Wi-Fi)

Question: does this work on AT&T network for sim? thanks Answer 1: Wifi only Answer 2: Sorry. This model is WIFI only. Answer 3: Yes Answer 4: It's a wifi tablet Answer 5: This version of the tablet does not have telephony features. It is Wi-Fi only, and should work on any typical network. I never had any issues. But it does NOT make cell phone calls (you can of course use Skype).


カスタマイズ

ツールキットは、提供されているサンプルやデータセットをそのまま使うだけでなく、独自のユースケースに合わせて拡張できます。
独自のデータセットを使う場合、data_processディレクトリにカスタムのReaderクラスを作成できます。
QandAFileReaderを参考に、データソースから文書を読み込み、検索用の構造に変換する処理を実装します。
インデックスマッピングmappingディレクトリのテンプレートをベースにカスタマイズできます。

サンプルスクリプト自体も拡張可能です。
examplesディレクトリのスクリプトは、共通のインターフェース(cmd_line_interface.py)を使っているため、独自のクエリロジックを組み込んだスクリプトを追加できます。
カスタム検索クエリを作成し、既存のCLIフレームワークと組み合わせることで、独自の検索パターンを試せます。

また、設定ファイルの柔軟性により、さまざまなOpenSearch環境での実験が可能です。
ローカル環境で動作確認した後、configs/osmlqs.yamlの設定を変更するだけで、Amazon OpenSearch Serviceやリモートのセルフマネージドクラスタに接続できます。
環境変数.envファイルによる設定の上書きもサポートしているため、環境ごとに異なる認証情報やエンドポイントを管理できます。

まとめ

opensearch-ml-quickstartは、OpenSearchの様々な検索をローカル環境ですぐに試せるツールキットです。
複数の検索アプローチを試せるサンプル、ローカルモデルと外部サービス間の移行を容易にする抽象化レイヤー、実際の製品データを使った実験環境が揃っています。 サンプルやデータセットは独自のものに置き換えられ、設定ファイルの変更だけでさまざまなOpenSearch環境に対応できます。
こうした環境で様々な方法を試し、理解を深めたり、新しい試みの実験ができると良いでしょう。