I Tried Keyword Search (Full-Text Search) and Hybrid Search with Amazon S3 Vectors

I Tried Keyword Search (Full-Text Search) and Hybrid Search with Amazon S3 Vectors

Amazon S3 Vectors now supports full-text search and hybrid search. I created an index in the AWS console and tried a search combining keyword search and vector search.
2026.12.02

This page has been translated by machine translation. View original

Introduction

Hi, I'm Kosuke from the AI Business Division.

On November 16, 2026, Amazon S3 Vectors added support for full-text search (keyword search) and hybrid search. Until now, S3 Vectors only supported vector search, so to find documents containing a specific string such as a product code or proper noun, you had to combine it with something like Amazon OpenSearch Service.

This article focuses on the AWS Management Console and walks through creating an index with full-text search enabled, then trying keyword search and hybrid search.

What is full-text search in S3 Vectors?

S3 Vectors is an S3 feature that stores vectors together with metadata and lets you run similarity search on them. With this update, text stored in metadata can now be made a target of full-text search.

Here is how it works.

  • In the index settings, you register the metadata keys to be searched by full-text search
  • The strings stored in those keys are split into words by an analyzer and scored with BM25
  • Search uses the existing QueryVectors API, and the parameters you pass determine the type of search
Parameters passed Search type How results are ranked
queryVector only Vector search Distance between vectors
queryTexts only Full-text search BM25
Both queryVector and queryTexts Hybrid search The two rankings are merged with Reciprocal Rank Fusion (RRF)

BM25 scores documents based on how many times the search term appears in a document and how rare that term is across all documents. RRF combines the rankings from vector search and full-text search into a single ranking, so results from two searches with different score units can be merged as they are.

By default, the language-agnostic standard analyzer is used. Language-specific analyzers are available for 10 languages, including English, Japanese, Chinese, and Korean, and you can choose one per metadata key.

Reference documents

https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-vectors-hybrid-search.html

https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-vectors-configuring-full-text-search.html

Architecture we'll build

  • S3 vector bucket sample-coffee-vectors and index beans: created in the console
  • Amazon Bedrock Titan Text Embeddings V2: embeddings for documents and queries (1024 dimensions)
  • Local PC: runs Python scripts (boto3) for writing data and searching

S3 Vectors stores only vectors and metadata, so you have to generate the embeddings yourself. The console only lets you manage buckets and indexes; writing vectors and searching must be done through the AWS CLI, SDK, or REST API. In this article, I write data and search from my local PC using Python scripts.

The flow is as follows. Creating the bucket and index, checking the settings, and adding a full-text search field are done in the S3 console, while writing data and searching are done from the local PC.

Prerequisites

  • Region: Tokyo (ap-northeast-1)
  • Environment: local PC (AWS credentials configured), Python 3.13, boto3 1.44.17. The full-text search parameters (queryTexts and textSearchConfigurations) are available in boto3 1.44.4 and later
  • Required permissions: S3 Vectors permissions and Bedrock's bedrock:InvokeModel. Searches using queryTexts need s3vectors:GetVectors in addition to s3vectors:QueryVectors
  • Bedrock model: amazon.titan-embed-text-v2:0
  • Test data: I prepared a product catalog of 16 coffee beans from a fictional company, "Sample Coffee Trading." Each item is one product, with a product name (title), roast level (category), and a description of origin and flavor (body)

Step 1: Create a vector bucket

Open the S3 console, then choose Vector buckets in the left menu → Create vector bucket.

Item Value
Vector bucket name sample-coffee-vectors
Server-side encryption Do not specify an encryption type (default)

The only input is the bucket name. If you don't specify an encryption type, encryption with Amazon S3 managed keys (SSE-S3) is used. The encryption setting can't be changed after creation, so if you want to use a KMS key, specify it here.

When you choose Create vector bucket, you return to the list, where the new bucket appears.

Step 2: Create an index with full-text search enabled

Choose Create vector index in the creation-complete message.

At the top of the bucket screen, a notice says to use the AWS CLI, AWS SDK, or REST API to insert, list, and query vectors. The console only lets you manage buckets and indexes; you can't write data or search from the console.

Enter the basic index settings under Properties on the creation screen.

Item Value
Vector index name beans
Dimensions 1024
Distance metric Cosine

Below that, under Metadata configuration - optional, there are two tabs: Full-text search metadata and Non-filterable metadata. First, on the Non-filterable metadata tab, add body as a key.

Next, switch to the Full-text search metadata tab and choose Add new key to open a dialog where you specify the key and analyzer.

Item Value
Key body
Analyzer Custom
Language Japanese

The analyzer has two options, Default (standard analyzer) and Custom; choosing Custom shows a language dropdown. There are 10 languages to choose from.

Some of the settings decided here can't be changed later.

  • Dimensions and distance metric
  • Non-filterable metadata keys
  • The analyzer of a full-text search field (to change it, remove the field from full-text search and add it again)

I made body non-filterable this time because of the metadata size limits. Filterable metadata is limited to 40 KB per vector and 2 KB per string, but if a key is non-filterable, you can put up to 100 KB into it as a full-text search field. Long text such as body text isn't used in filter conditions, so I made it non-filterable.

To create the same index with the AWS CLI, use the following command. The console's "Custom" and language selection correspond to language in textSearchConfigurations.

aws s3vectors create-index \
  --vector-bucket-name sample-coffee-vectors \
  --index-name beans \
  --data-type float32 \
  --dimension 1024 \
  --distance-metric cosine \
  --metadata-configuration '{"nonFilterableMetadataKeys": ["body"], "textSearchConfigurations": [{"metadataKey": "body", "language": "ja"}]}'

Reference documents

https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-vectors-create-index.html

https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-vectors-configuring-full-text-search.html

https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-vectors-limitations.html

Step 3: Check the index mode and full-text search settings

Open the created index beans to check the index mode and full-text search settings on the detail screen.

There are two things to look at.

  • Enhanced index mode under Vector index summary should be "Enabled". This is ENHANCED mode, the state in which full-text search and hybrid search can be used. Choosing "Enabled" shows an explanation: a metadata filter is applied before vector search, and the prefix-match $startsWith operator can be used. For a newly created vector bucket like this one, it is enabled from the start
  • Under Metadata configuration, Full-text search metadata should list body with the status "Active" and the analyzer setting "Japanese". Once the status is Active, you can run full-text search and hybrid search on that key

Reference document

https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-vectors-index-mode.html

Step 4: Write the sample data

From here on, we work on the local PC. Place the following four files in a working folder.

  • documents.json (16 sample documents)
  • 01_put_vectors.py
  • 02_query.py
  • 03_check_vectors.py

If your boto3 is old, update it.

pip install -U boto3

The contents of documents.json are as follows.

{
  "disclaimer": "※ 本資料はブログ検証用に生成した架空企業「サンプル珈琲商事」のダミー文書です。実在の企業・人物・製品とは関係ありません。",
  "documents": [
    {
      "key": "bean-01",
      "title": "エチオピア イルガチェフェ ウォッシュド",
      "category": "浅煎り",
      "body": "エチオピア南部のイルガチェフェ地区で収穫された豆を、水洗式で精製しました。ジャスミンのような花の香りがあり、冷めるとレモンティーを思わせる後味に変わります。浅煎りで、ペーパードリップに向いています。商品コードは B-201 です。"
    },
    {
      "key": "bean-02",
      "title": "エチオピア グジ ナチュラル",
      "category": "浅煎り",
      "body": "エチオピアのグジ地区の豆を、果肉を付けたまま天日で乾燥させるナチュラル精製で仕上げました。完熟したベリーの甘い香りと、赤ワインのような余韻があります。香りの個性が強いので、まずはブラックで試してください。商品コードは B-202 です。"
    },
    {
      "key": "bean-03",
      "title": "ケニア ニエリ ウォッシュド",
      "category": "中浅煎り",
      "body": "ケニア山のふもと、ニエリ地区の農協から届いた豆です。カシスやグレープフルーツのような、はっきりした酸があります。アイスにしても味が薄まりにくく、夏場によく出ます。商品コードは B-203 です。"
    },
    {
      "key": "bean-04",
      "title": "コロンビア ウイラ ウォッシュド",
      "category": "中煎り",
      "body": "コロンビア南部のウイラ県で、標高 1,700 m 前後の小規模農園が育てた豆です。キャラメルの甘さとオレンジのような酸がほどよく釣り合っていて、飲む人を選びません。初めて注文する方におすすめしています。商品コードは B-204 です。"
    },
    {
      "key": "bean-05",
      "title": "グアテマラ アンティグア ウォッシュド",
      "category": "中煎り",
      "body": "火山に囲まれたグアテマラのアンティグア盆地の豆です。ミルクチョコレートとローストしたナッツの風味があり、後味はすっきりしています。焼き菓子と合わせる喫茶店からの注文が多い商品です。商品コードは B-205 です。"
    },
    {
      "key": "bean-06",
      "title": "ブラジル セラード ナチュラル",
      "category": "中深煎り",
      "body": "ブラジルのセラード台地の大規模農園で、ナチュラル精製された豆です。ピーナッツのような香ばしさがあり、酸はほとんど感じません。単体でも飲めますが、ブレンドの土台として使われることが多い豆です。商品コードは B-206 です。"
    },
    {
      "key": "bean-07",
      "title": "インドネシア マンデリン スマトラ式",
      "category": "深煎り",
      "body": "スマトラ島北部のマンデリンを、現地特有のスマトラ式で精製しました。ハーブや湿った土を思わせる独特の香りと、重たいコクがあります。深煎りにしても個性が残るので、好みがはっきり分かれる豆です。商品コードは B-207 です。"
    },
    {
      "key": "bean-08",
      "title": "コスタリカ タラス ハニー",
      "category": "中煎り",
      "body": "コスタリカのタラス地区の豆を、果肉の粘液質を残して乾燥させるハニー精製で仕上げました。はちみつのようななめらかな甘さと、りんごのような酸があります。商品コードは B-208 です。"
    },
    {
      "key": "bean-09",
      "title": "ルワンダ フイエ ウォッシュド",
      "category": "中浅煎り",
      "body": "ルワンダ南部のフイエ地区の水洗式の豆です。紅茶のような軽い口当たりで、アプリコットの甘酸っぱさがあります。渋みが少なく、冷めてもおいしく飲めます。商品コードは B-209 です。"
    },
    {
      "key": "bean-10",
      "title": "パナマ ボケテ ゲイシャ ウォッシュド",
      "category": "浅煎り",
      "body": "パナマのボケテ地区で栽培された希少品種ゲイシャです。ベルガモットや白い花の華やかな香りがあり、後味は長く続きます。入荷量が少ないため、1 回の注文は 5 kg までとさせていただきます。商品コードは B-210 です。"
    },
    {
      "key": "bean-11",
      "title": "ブレンド 朝の定番",
      "category": "中深煎り",
      "body": "ブラジル セラードとコロンビア ウイラを 6 対 4 で合わせたブレンドです。香ばしさと甘さが中心で、毎日飲んでも飽きない味を目指しました。喫茶店のモーニング用として最も多く出荷しています。商品コードは B-211 です。"
    },
    {
      "key": "bean-12",
      "title": "ブレンド 午後のラテ",
      "category": "深煎り",
      "body": "ミルクと合わせたときに味の輪郭が残るように、マンデリンとブラジルを深く焼いて合わせました。ビターチョコレートのようなほろ苦さがあり、砂糖を入れても風味が負けません。商品コードは B-212 です。"
    },
    {
      "key": "bean-13",
      "title": "デカフェ コロンビア",
      "category": "中煎り",
      "body": "コロンビア産の豆から、水だけを使う方法でカフェインを 99.9 % 取り除きました。風味の抜けが少なく、ナッツと黒糖のような甘さがあります。妊娠中や授乳中の方がいるお店からの注文が増えています。商品コードは B-213 です。"
    },
    {
      "key": "bean-14",
      "title": "ブレンド エスプレッソ用",
      "category": "深煎り",
      "body": "高い圧力で短時間に抽出しても酸が尖らないように配合したブレンドです。抽出すると厚いクレマができ、ダークチョコレートとカラメルの風味があります。極細挽きでの出荷にも対応します。商品コードは B-214 です。"
    },
    {
      "key": "bean-15",
      "title": "水出し用パック",
      "category": "深煎り",
      "body": "粗く挽いた深煎りの豆を、1 リットル用の不織布パックに詰めました。ポットに入れて冷蔵庫で 8 時間置くだけで、雑味の少ないすっきりした一杯になります。5 月から 9 月までの季節商品です。商品コードは B-215 です。"
    },
    {
      "key": "bean-16",
      "title": "ドリップバッグ 5 種詰め合わせ",
      "category": "詰め合わせ",
      "body": "カップに掛けてお湯を注ぐだけの個包装を、浅煎りから深煎りまで 5 種類、各 4 袋ずつ箱に入れました。のし紙と手提げ袋を無料で付けられます。お中元とお歳暮の時期は、発送まで 5 営業日かかります。商品コードは B-216 です。"
    }
  ]
}

01_put_vectors.py converts each document's title and body into an embedding with Titan Text Embeddings V2 and writes it with PutVectors.

"""サンプル文書を埋め込みに変換して S3 Vectors のインデックスに書き込む。

使い方(boto3 1.44.4 以降が必要):
    python3 01_put_vectors.py

バケット名・インデックス名を変えた場合は環境変数で上書きする:
    VECTOR_BUCKET=my-bucket VECTOR_INDEX=my-index python3 01_put_vectors.py
"""

import json
import os
from pathlib import Path

import boto3

REGION = os.environ.get("AWS_REGION", "ap-northeast-1")
VECTOR_BUCKET = os.environ.get("VECTOR_BUCKET", "sample-coffee-vectors")
VECTOR_INDEX = os.environ.get("VECTOR_INDEX", "beans")
EMBEDDING_MODEL_ID = "amazon.titan-embed-text-v2:0"
DIMENSION = 1024

# documents.json はこのスクリプトと同じフォルダ、または ../data/ に置く
HERE = Path(__file__).resolve().parent
DATA_FILE = next(p for p in (HERE / "documents.json", HERE.parent / "data" / "documents.json") if p.exists())

bedrock = boto3.client("bedrock-runtime", region_name=REGION)
s3vectors = boto3.client("s3vectors", region_name=REGION)

def embed(text: str) -> list[float]:
    """Titan Text Embeddings V2 で 1024 次元の埋め込みを作る。"""
    response = bedrock.invoke_model(
        modelId=EMBEDDING_MODEL_ID,
        body=json.dumps({"inputText": text, "dimensions": DIMENSION, "normalize": True}),
    )
    return json.loads(response["body"].read())["embedding"]

def main() -> None:
    documents = json.loads(DATA_FILE.read_text(encoding="utf-8"))["documents"]

    # ---------- 埋め込みの生成 ----------
    vectors = []
    for doc in documents:
        vectors.append(
            {
                "key": doc["key"],
                "data": {"float32": embed(f"{doc['title']}\n{doc['body']}")},
                # title と body が全文検索の対象になるメタデータ
                "metadata": {
                    "title": doc["title"],
                    "category": doc["category"],
                    "body": doc["body"],
                },
            }
        )
        print(f"embedded: {doc['key']} {doc['title']}")

    # ---------- 書き込み ----------
    s3vectors.put_vectors(
        vectorBucketName=VECTOR_BUCKET,
        indexName=VECTOR_INDEX,
        vectors=vectors,
    )
    print(f"put_vectors: {len(vectors)} 件を {VECTOR_BUCKET}/{VECTOR_INDEX} に書き込みました")

if __name__ == "__main__":
    main()

Run it.

python3 01_put_vectors.py

The result is as follows. Generating and writing the 16 embeddings took about 15 seconds in total.

embedded: bean-01 エチオピア イルガチェフェ ウォッシュド
embedded: bean-02 エチオピア グジ ナチュラル
(中略)
embedded: bean-16 ドリップバッグ 5 種詰め合わせ
put_vectors: 16 件を sample-coffee-vectors/beans に書き込みました

To verify what was written, use ListVectors and GetVectors.

I prepared 03_check_vectors.py for checking. It lists the vectors in the index with ListVectors and retrieves one by key with GetVectors.

"""S3 Vectors に書き込んだ内容を ListVectors と GetVectors で確かめる。

使い方:
    python3 03_check_vectors.py
"""

import json
import os

import boto3

REGION = os.environ.get("AWS_REGION", "ap-northeast-1")
VECTOR_BUCKET = os.environ.get("VECTOR_BUCKET", "sample-coffee-vectors")
VECTOR_INDEX = os.environ.get("VECTOR_INDEX", "beans")

s3vectors = boto3.client("s3vectors", region_name=REGION)

def main() -> None:
    # ---------- ListVectors: list of keys ----------
    vectors = []
    params = {"vectorBucketName": VECTOR_BUCKET, "indexName": VECTOR_INDEX, "returnMetadata": True}
    while True:
        response = s3vectors.list_vectors(**params)
        vectors.extend(response["vectors"])
        if "nextToken" not in response:
            break
        params["nextToken"] = response["nextToken"]

    print(f"list_vectors: {len(vectors)} 件")
    for item in sorted(vectors, key=lambda v: v["key"]):
        print(f"  {item['key']} {item['metadata']['title']}")

    # ---------- GetVectors: get one item by key ----------
    response = s3vectors.get_vectors(
        vectorBucketName=VECTOR_BUCKET,
        indexName=VECTOR_INDEX,
        keys=["bean-07"],
        returnData=True,
        returnMetadata=True,
    )
    item = response["vectors"][0]
    print(f"get_vectors: {item['key']}")
    print(f"  ベクトルの次元数: {len(item['data']['float32'])}")
    print(f"  metadata: {json.dumps(item['metadata'], ensure_ascii=False, indent=2)}")

if __name__ == "__main__":
    main()
python3 03_check_vectors.py

The result is as follows.

list_vectors: 16 件
  bean-01 エチオピア イルガチェフェ ウォッシュド
  bean-02 エチオピア グジ ナチュラル
  bean-03 ケニア ニエリ ウォッシュド
  bean-04 コロンビア ウイラ ウォッシュド
  bean-05 グアテマラ アンティグア ウォッシュド
  bean-06 ブラジル セラード ナチュラル
  bean-07 インドネシア マンデリン スマトラ式
  bean-08 コスタリカ タラス ハニー
  bean-09 ルワンダ フイエ ウォッシュド
  bean-10 パナマ ボケテ ゲイシャ ウォッシュド
  bean-11 ブレンド 朝の定番
  bean-12 ブレンド 午後のラテ
  bean-13 デカフェ コロンビア
  bean-14 ブレンド エスプレッソ用
  bean-15 水出し用パック
  bean-16 ドリップバッグ 5 種詰め合わせ
get_vectors: bean-07
  ベクトルの次元数: 1024
  metadata: {
  "title": "インドネシア マンデリン スマトラ式",
  "body": "スマトラ島北部のマンデリンを、現地特有のスマトラ式で精製しました。ハーブや湿った土を思わせる独特の香りと、重たいコクがあります。深煎りにしても個性が残るので、好みがはっきり分かれる豆です。商品コードは B-207 です。",
  "category": "深煎り"
}

We confirmed that all 16 items are stored. bean-07 holds a 1024-dimension vector and three metadata fields: title, body, and category. With ListVectors and GetVectors, you can also retrieve metadata by adding returnMetadata=True.

For searching, we use 02_query.py. The first argument switches the search type (vector / text / hybrid).

"""S3 Vectors にベクトル検索 / 全文検索 / ハイブリッド検索を投げて結果を並べる。

使い方(boto3 1.44.4 以降が必要):
    python3 02_query.py vector "マンデリン"
    python3 02_query.py text "マンデリン"
    python3 02_query.py hybrid "マンデリン"
    python3 02_query.py text "朝の定番" --fields body,title   # 複数フィールドを検索
"""

import argparse
import json
import os

import boto3

REGION = os.environ.get("AWS_REGION", "ap-northeast-1")
VECTOR_BUCKET = os.environ.get("VECTOR_BUCKET", "sample-coffee-vectors")
VECTOR_INDEX = os.environ.get("VECTOR_INDEX", "beans")
EMBEDDING_MODEL_ID = "amazon.titan-embed-text-v2:0"
DIMENSION = 1024

bedrock = boto3.client("bedrock-runtime", region_name=REGION)
s3vectors = boto3.client("s3vectors", region_name=REGION)

def embed(text: str) -> list[float]:
    """Titan Text Embeddings V2 で 1024 次元の埋め込みを作る。"""
    response = bedrock.invoke_model(
        modelId=EMBEDDING_MODEL_ID,
        body=json.dumps({"inputText": text, "dimensions": DIMENSION, "normalize": True}),
    )
    return json.loads(response["body"].read())["embedding"]

def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("mode", choices=["vector", "text", "hybrid"])
    parser.add_argument("query")
    parser.add_argument("--fields", default="body", help="全文検索するメタデータキー(カンマ区切り)")
    parser.add_argument("--top-k", type=int, default=5)
    args = parser.parse_args()

    params = {
        "vectorBucketName": VECTOR_BUCKET,
        "indexName": VECTOR_INDEX,
        "topK": args.top_k,
        "returnMetadata": True,
    }

    # ---------- 検索の種類は渡すパラメータで決まる ----------
    # queryVector のみ → ベクトル検索 / queryTexts のみ → 全文検索 / 両方 → ハイブリッド検索
    if args.mode in ("vector", "hybrid"):
        params["queryVector"] = {"float32": embed(args.query)}
        params["returnDistance"] = True
    if args.mode in ("text", "hybrid"):
        params["queryTexts"] = [{"text": args.query, "metadataKey": key} for key in args.fields.split(",")]
        params["returnScores"] = True

    response = s3vectors.query_vectors(**params)

    # ---------- 結果の表示 ----------
    print(f"[{args.mode}] {args.query}")
    for rank, item in enumerate(response["vectors"], start=1):
        # metadata 以外(distance やスコア)は返ってきたものをそのまま表示する
        scores = {k: v for k, v in item.items() if k not in ("key", "metadata")}
        title = item.get("metadata", {}).get("title", "")
        print(f"{rank}. {item['key']} {title} {json.dumps(scores, ensure_ascii=False)}")

if __name__ == "__main__":
    main()

For full-text search, pass queryTexts as pairs of the search term (text) and the metadata key to search (metadataKey). Adding returnScores returns the BM25 score.

Searching by origin name

First, we retrieve the origin name "Mandheling" with full-text search and vector search. "Mandheling" appears in the body of two items: bean-07 (Indonesia Mandheling) and bean-12 (a blend that uses Mandheling).

python3 02_query.py text "マンデリン"
python3 02_query.py vector "マンデリン"

Full-text search results:

[text] マンデリン
1. bean-12 ブレンド 午後のラテ {"scores": {"bm25Scores": [{"metadataKey": "body", "score": 2.0912702083587646}]}}
2. bean-07 インドネシア マンデリン スマトラ式 {"scores": {"bm25Scores": [{"metadataKey": "body", "score": 1.8697949647903442}]}}

topK is 5, but only the 2 items containing "Mandheling" were hit; with full-text search, documents that don't contain the search term don't appear in the results. Because we added returnScores, bm25Scores under scores contains the BM25 score for each searched metadata key.

Vector search results:

[vector] マンデリン
1. bean-07 インドネシア マンデリン スマトラ式 {"distance": 0.6769039034843445}
2. bean-12 ブレンド 午後のラテ {"distance": 0.8291053771972656}
3. bean-11 ブレンド 朝の定番 {"distance": 0.9046759605407715}
4. bean-06 ブラジル セラード ナチュラル {"distance": 0.927362859249115}
5. bean-01 エチオピア イルガチェフェ ウォッシュド {"distance": 0.9299783110618591}

Here the top 2 are the same two items, and beans that don't contain "Mandheling" follow from 3rd place. Vector search always returns topK items in order of closeness, so you can't tell from the results how many documents actually match. distance is cosine distance, where smaller means closer.

Searching by processing method

Next, we search for the processing method "Natural". "Natural" is written in the body of bean-02 and bean-06.

python3 02_query.py text "ナチュラル"
python3 02_query.py vector "ナチュラル"
[text] ナチュラル
1. bean-06 ブラジル セラード ナチュラル {"scores": {"bm25Scores": [{"metadataKey": "body", "score": 1.9586957693099976}]}}
2. bean-02 エチオピア グジ ナチュラル {"scores": {"bm25Scores": [{"metadataKey": "body", "score": 1.8697949647903442}]}}
[vector] ナチュラル
1. bean-02 エチオピア グジ ナチュラル {"distance": 0.6714208722114563}
2. bean-06 ブラジル セラード ナチュラル {"distance": 0.745478630065918}
3. bean-05 グアテマラ アンティグア ウォッシュド {"distance": 0.8550398945808411}
4. bean-15 水出し用パック {"distance": 0.8885090947151184}
5. bean-09 ルワンダ フイエ ウォッシュド {"distance": 0.8924821615219116}

The same tendency as with the origin name appeared. Full-text search retrieved only the 2 natural-process items, while vector search had the same 2 in the top 2 and then included washed beans and the cold-brew pack from 3rd place.

Searching by product code

We also try a string of symbols and digits like a product code. B-213 is the product code of bean-13 (Decaf Colombia).

python3 02_query.py text "B-213"
python3 02_query.py vector "B-213"
[text] B-213
1. bean-13 デカフェ コロンビア {"scores": {"bm25Scores": [{"metadataKey": "body", "score": 2.3971810340881348}]}}
2. bean-08 コスタリカ タラス ハニー {"scores": {"bm25Scores": [{"metadataKey": "body", "score": 0.03312872722744942}]}}
3. bean-09 ルワンダ フイエ ウォッシュド {"scores": {"bm25Scores": [{"metadataKey": "body", "score": 0.03256814554333687}]}}
4. bean-12 ブレンド 午後のラテ {"scores": {"bm25Scores": [{"metadataKey": "body", "score": 0.03256814554333687}]}}
5. bean-14 ブレンド エスプレッソ用 {"scores": {"bm25Scores": [{"metadataKey": "body", "score": 0.03150203824043274}]}}
[vector] B-213
1. bean-06 ブラジル セラード ナチュラル {"distance": 0.8815993666648865}
2. bean-12 ブレンド 午後のラテ {"distance": 0.8835493922233582}
3. bean-11 ブレンド 朝の定番 {"distance": 0.8986483812332153}
4. bean-15 水出し用パック {"distance": 0.9022520184516907}
5. bean-03 ケニア ニエリ ウォッシュド {"distance": 0.9093639254570007}

In full-text search, bean-13 ranked first with a score of 2.40. The other 4 items from 2nd place on were around 0.03, a difference of about 70x from first place. Every document has a sentence like "The product code is B-2xx", so B-213 is probably split into "B" and "213", and the part shared by every document likely matches weakly. With a score gap this large, you can separate them with a threshold, so it doesn't seem to be a problem in operation.

In vector search, bean-13 didn't make the top 5. A string of symbols and digits has no semantic clue, so it isn't hit by vector closeness.

Reference document

https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-vectors-querying-full-text-and-vector-search.html

A query that keyword search can't retrieve

The three queries in Step 5 were ones where the search term appears as-is in the body. This time we try a query ("a coffee that won't keep me awake even if I drink it before bed") that doesn't use the same words as the body. bean-13 is a decaffeinated bean, but words like "before bed" and "can't sleep" don't appear in its body.

python3 02_query.py text "寝る前に飲んでも眠れなくならないコーヒー"
python3 02_query.py vector "寝る前に飲んでも眠れなくならないコーヒー"
[text] 寝る前に飲んでも眠れなくならないコーヒー
1. bean-11 ブレンド 朝の定番 {"scores": {"bm25Scores": [{"metadataKey": "body", "score": 1.8697949647903442}]}}
2. bean-04 コロンビア ウイラ ウォッシュド {"scores": {"bm25Scores": [{"metadataKey": "body", "score": 1.7886139154434204}]}}

[vector] 寝る前に飲んでも眠れなくならないコーヒー
1. bean-11 ブレンド 朝の定番 {"distance": 0.8032991290092468}
2. bean-13 デカフェ コロンビア {"distance": 0.8960756063461304}
3. bean-07 インドネシア マンデリン スマトラ式 {"distance": 0.9135008454322815}
4. bean-04 コロンビア ウイラ ウォッシュド {"distance": 0.914107620716095}
5. bean-02 エチオピア グジ ナチュラル {"distance": 0.917869508266449}

In full-text search, bean-13 wasn't hit, and 2 items containing the same verb as "drink" in the query were hit. In vector search, bean-13, whose body contains none of the same words as the query, ranked 2nd.

Passing both queryVector and queryTexts makes it a hybrid search. S3 Vectors runs vector search and full-text search separately, then merges the two rankings with RRF and returns the result.

python3 02_query.py hybrid "寝る前に飲んでも眠れなくならないコーヒー"
[hybrid] 寝る前に飲んでも眠れなくならないコーヒー
1. bean-11 ブレンド 朝の定番 {"distance": 0.8032991290092468, "scores": {"fused": 0.03333333507180214, "bm25Scores": [{"metadataKey": "body", "score": 1.8697949647903442}], "vectorDistance": 0.8032991290092468}}
2. bean-04 コロンビア ウイラ ウォッシュド {"distance": 0.914107620716095, "scores": {"fused": 0.03226646035909653, "bm25Scores": [{"metadataKey": "body", "score": 1.7886139154434204}], "vectorDistance": 0.914107620716095}}
3. bean-13 デカフェ コロンビア {"distance": 0.8960756063461304, "scores": {"fused": 0.016393441706895828, "vectorDistance": 0.8960756063461304}}
4. bean-07 インドネシア マンデリン スマトラ式 {"distance": 0.9135008454322815, "scores": {"fused": 0.016129031777381897, "vectorDistance": 0.9135008454322815}}
5. bean-02 エチオピア グジ ナチュラル {"distance": 0.917869508266449, "scores": {"fused": 0.015625, "vectorDistance": 0.917869508266449}}

fused under scores is the merged score, and results are sorted by this value in descending order. bm25Scores and vectorDistance are attached only to documents that appeared in the respective search results.

A query mixing an origin name and paraphrasing

Next, we try a query ("a bean that goes well with cow's milk, made with Mandheling") where bean-12 (Afternoon Latte) is the expected answer. bean-12's body contains "Mandheling", but it says "milk" instead of "cow's milk". I ran the same query with all three search types and lined up the top 5.

python3 02_query.py hybrid "マンデリンを使った牛乳に合う豆"
python3 02_query.py text "マンデリンを使った牛乳に合う豆"
python3 02_query.py vector "マンデリンを使った牛乳に合う豆"
Rank Full-text search Vector search Hybrid search
1 bean-06 bean-07 bean-07
2 bean-07 bean-12 bean-06
3 bean-13 bean-06 bean-12
4 bean-12 bean-03 bean-13
5 bean-08 bean-05 bean-03

bean-12 ranked 4th in full-text search, 2nd in vector search, and 3rd in hybrid search. The top result of full-text search was bean-06, which doesn't contain "Mandheling"; its body text "is often used" seems to have matched "used" and "bean" in the query. If you pass a sentence-style query straight to full-text search, it also matches such generic words, and that ranking is reflected in the hybrid search too.

Reference document

https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-vectors-querying-full-text-and-vector-search.html

Step 7: Add a full-text search field to an existing index

Full-text search fields can be added even after the index has been created. So far title hasn't been a full-text search target, so let's add it from the console.

This is the index detail screen before adding. There is only one full-text search metadata key, body.

Choosing Add new key on the Full-text search metadata tab takes you to the "Add full-text search metadata key" screen. Existing keys are listed below, and a note at the bottom of the screen says that if data already exists, building the index can take from several minutes to several hours.

Choosing Add new key on this screen opens the same dialog as at index creation. Specify title as the key, Custom as the analyzer, and Japanese as the language, choose Add, and finally choose Save changes.

This is the detail screen after saving. There are now two full-text search metadata keys, and the status of title is also Active.

Only 16 items are stored this time, so the build finished in under 10 seconds and the status became Active right away. With larger amounts of data, wait until the status becomes Active before searching.

Now that title has been added, let's search for the blend name "Morning Staple". This blend name appears only in bean-11's product name (title), not in the body (body). Use --fields to specify the metadata keys to search, and compare the case of body only with the case of both body and title.

python3 02_query.py text "朝の定番" --fields body
python3 02_query.py text "朝の定番" --fields body,title
[text] 朝の定番

[text] 朝の定番
1. bean-11 ブレンド 朝の定番 {"scores": {"bm25Scores": [{"metadataKey": "title", "score": 5.0867109298706055}]}}

When searching body only, nothing was hit, and adding title retrieved bean-11. bm25Scores contains the metadata key that matched, so you can see the match was on title. Without rewriting the data, the title of the vectors already stored became a full-text search target.

An index can have up to 10 full-text search fields registered, and a single query can search up to 10 fields.

Reference documents

https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-vectors-configuring-full-text-search.html

https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-vectors-limitations.html

About pricing

Finally, let's touch on S3 Vectors pricing. Full-text search and hybrid search have no dedicated pricing items; they are charged under the same items as the existing S3 Vectors. The US East (N. Virginia) unit prices listed on the pricing page are as follows.

Item Unit price Notes
Storage 0.06 USD / GB-month Total size of vectors, metadata, and keys
Writes (PUT) 0.20 USD / GB Calculated with a minimum of 128 KB per PUT
Query requests 2.50 USD / million queries
Data processed by queries Vectors: tiered by index size; text to be searched: flat rate (both per TB)
Data retrieved as query results 0.01 USD / GB First 512 KB per query is free

Points worth knowing when using full-text search:

  • Metadata made a full-text search target is also included in storage and write sizes
  • Metadata used for both filtering and full-text search is counted twice toward storage size. Making body non-filterable this time avoids waste in this respect too
  • If you later make existing metadata a full-text search target, building the index (backfill) is charged at the same unit price as writes. The operation of adding title in Step 7 corresponds to this

This test used 16 vectors (under 100 KB in total) and about 20 queries, so the S3 Vectors charge stays under 0.01 USD even when calculated with the unit prices above. In addition, there is a charge for Amazon Bedrock's Titan Text Embeddings V2, which was used to generate embeddings, but that was only about 40 conversions of short text. There's no need to keep a cluster running as with OpenSearch, and you pay only for what you use, so it's easy to try on a small scale.

Reference document

https://aws.amazon.com/jp/s3/pricing/

Cleanup

S3 Vectors is charged according to the amount of stored data and queries. The amount here is negligible, but delete everything once the verification is done.

  1. In the S3 console, go to Vector buckets → sample-coffee-vectors → select the index beans and delete it
  2. Delete the vector bucket sample-coffee-vectors

A vector bucket can't be deleted until all indexes in it have been deleted.

Conclusion

This article covered creating an index with full-text search enabled in S3 Vectors from the console, then trying keyword search and hybrid search.

It's convenient that simply adding queryTexts to QueryVectors makes it a hybrid search.

On the other hand, as of this writing, hybrid search on S3 Vectors can't be used from Amazon Bedrock Knowledge Bases. If you want to use hybrid search for RAG, the setup would likely be to call S3 Vectors' QueryVectors directly to retrieve chunks, include those chunks in the prompt, and generate the answer with the Converse API.

Thank you for reading to the end!

References

Share this article

AWSのお困り事はクラスメソッドへ