5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【AWS】知識ゼロからBedrock + S3VectorでRAG構築に挑戦!気になったポイントも書いてみた

Posted at

【AWS】知識ゼロからBedrock + S3VectorでRAG構築に挑戦!気になったポイントも書いてみた

概要

本記事では、Amazon Bedrockの機能である Knowledge Bases を活用し、S3に保存した独自のドキュメント(Markdown)に基づいた回答を生成するRAG(Retrieval-Augmented Generation)システムを構築した結果と構築中に気になった点について書いてみました!

従来のRAG構築では、ドキュメントの分割、ベクトル化、データベースへの登録といったパイプラインを自作する必要がありましたが、Knowledge Basesを使うことでこれらをフルマネージドで完結させることができます。

今回は以下の記事を参考にRAGを構築してみました!
Amazon S3 Vectors をベクトルストアにした Amazon Bedrock Knowledge Bases のノーコード RAG 構築をゼロから解説

今回設定・用意したもの

設定したベクトル埋め込みモデル

Titan Text Embeddingsv2を使用しました!

項目 詳細
最大入力トークン数 8192トークン
出力次元数 256, 512, 1,024
対応言語 100以上の言語(日本語含む)およびコード(プログラミング言語)
主なパラメータ inputText, dimensions, normalize
価格目安 $0.0001 / 1,000 トークン(2025年時点の標準的な従量課金)

用意した資料

今回ナレッジベースに読み込ませる資料としてはAIに吐かせたSpringBootを使用したJavaの基本設計書10点としました!

1.E-admin_user_deactivation.md

Basic Design: Admin Console - User Suspension
1. Authorization Rules
Annotate service methods with @PreAuthorize("hasRole('ADMIN')").

2. Process Details
Status Update: Update the users.is_active flag to false.

Session Invalidation: If the target user is currently logged in, forcibly invalidate their session using SessionRegistry.

2.E-auth_login_api.md

Basic Design: User Login Functionality
1. Interface
Path: /api/v1/auth/login (POST)

Request Body:

JSON

{
  "email": "string",
  "password": "string"
}
Response: 200 OK (Set-Cookie: JSESSIONID)

2. Process Details
Search for an active email address using UserRepository.

Verify the input password against the stored hash using BCryptPasswordEncoder.

Upon successful authentication, store the authentication object in Spring Security's SecurityContextHolder.

Record the current timestamp in the last_login_at column of the users table.

3.E-cart_item_addition.md

Basic Design: Add to Cart Functionality
1. Overview
Verify the current inventory level and save the item data to the cart table (CART_ITEMS).

2. Concurrency Control Policy
Inventory Check: Perform an inventory check at the time of adding an item to the cart, in addition to the final order confirmation.

Conflict Avoidance: Apply "Pessimistic Locking" when updating the stock in the product master to prevent data inconsistency.

4.E-common_audit_logging.md

Basic Design: Common Audit Log Specification
1. Scope of Logging
All API requests involving "Update" or "Delete" operations.

2. Log Fields
Execution timestamp, User ID, Request IP address, and Class/Method name.

Data delta (diff) between pre-update (Old) and post-update (New) states in JSON format.

Sensitive information (e.g., passwords) must be masked with *****.

5.E-monthly_sales_batch.md

Basic Design: Monthly Sales Aggregation
1. Execution Schedule
Every 1st day of the month at 2:00 AM (configured via Cron).

2. Processing Steps
Extraction: Retrieve records from the ORDERS table with the status "Completed" from the previous month.

Transformation: Apply currency exchange rate conversion logic.

Output: Insert the aggregated data into the MONTHLY_SALES table.

Error Handling: The process must be "Restartable"; in case of failure, it should resume from the record following the last successful one.

6.E-order_data_integration_api.md

Basic Design: Order Integration with Logistics System
1. Data Format
Format: JSON (UTF-8)

Field Mapping: order_id -> ref_no, item_id -> sku_code

2. Timeout Configuration
Connect Timeout: 2000ms / Read Timeout: 5000ms

Error Handling: Upon the 3rd failure, send a Slack notification to the administrator and set the process status to "Pending Manual Retry."

7.E-password_reset_email.md

Basic Design: Password Reset Request
1. Process Flow
User submits their email address.

System generates a "One-Time Token" valid for 24 hours.

Asynchronous Processing: Communcate with the mail server using @Async.

Immediately display a "Request Sent" message on the user's screen.

2. Exception Handling
In the event of a mail delivery failure, output an error log.

To maintain security, the user interface must display a generic message such as "An email has been sent if the account exists" to hide whether or not the email address is registered.

8.E-product_search_pagination.md

Basic Design: Product Search Functionality
1. Search Criteria
Category: Exact match.

Product Name: Partial match (fuzzy search).

Price Range: Min/Max range filters.

Sort Order: Newest arrival (default), price (ascending).

2. Implementation Specifications
Pagination: Utilize the Pageable object with a fixed size of 20 items per page.

Data Fetching: Generate dynamic queries using Specification (Criteria API).

Optimization: To reduce payload size, large text fields (such as full product descriptions) must be excluded from the list-view DTO.

9.E-profile_image_upload.md

Basic Design: Profile Image Update
1. Specifications
Storage Location: AWS S3 profiles/ directory.

Database Content: Store the S3 object key (not the full URL).

2. Validation and Processing
File Format: Limited to image/jpeg and image/png.

Size Limit: Maximum 2MB.

Resizing: Perform server-side scaling to 400x400px before saving to storage.

10.E-user_registration_validation.md

Basic Design: Member Registration Validation Rules
User ID: [a-zA-Z0-9]{8,20} (Alphanumeric only, 8 to 20 characters).

Password: Must contain at least one uppercase letter, one lowercase letter, and one digit.

Date of Birth: Future dates are not allowed (Validation error).

Address: Perform a consistency check between the postal code and the prefecture (via external API).

実行結果

BedrockのナレッジベースをテストからモデルNova 2 Liteを使用して行いました。

プロンプト

あなたはJava(Spring Boot)のシニアアーキテクトです。 以下の「設計レビュー用チェックリスト」に基づき、提出された「設計書」のレビューを行ってください。

1. 設計レビュー用チェックリスト(構造化データ)
YAML

project: "Spring Boot Design Review Checklist"
version: "1.0"
categories:
  - category: "Presentation Layer"
    items:
      - id: "C01"
        check_point: "Selection of @RestController vs @Controller"
        detail: "Standardize usage: @RestController for APIs, @Controller for views."
      - id: "C02"
        check_point: "DTO Utilization"
        detail: "Use dedicated DTOs for req/res instead of Entities."
      - id: "C03"
        check_point: "Validation Localization"
        detail: "Perform format checks at entry point using @Valid/@Validated."

  - category: "Business Layer"
    items:
      - id: "S01"
        check_point: "Transaction Boundaries"
        detail: "Apply @Transactional appropriately to guarantee atomicity."
      - id: "S02"
        check_point: "Constructor Injection"
        detail: "Prioritize constructor injection for better testability."
      - id: "S03"
        check_point: "Stateless Design"
        detail: "Avoid holding user-specific state in singleton bean instances."

  - category: "Persistence Layer"
    items:
      - id: "D01"
        check_point: "N+1 Problem Prevention"
        detail: "Use EntityGraph or Join Fetch to suppress redundant queries."
      - id: "D02"
        check_point: "Pagination Implementation"
        detail: "Apply Pageable for large dataset retrieval."
      - id: "D03"
        check_point: "Concurrency Control"
        detail: "Consider optimistic (@Version) or pessimistic locking."

  - category: "Security & Error Handling"
    items:
      - id: "X01"
        check_point: "Global Exception Handling"
        detail: "Unify error responses using @ControllerAdvice."
      - id: "X02"
        check_point: "Secret Externalization"
        detail: "Inject sensitive data via environment variables."
      - id: "X03"
        check_point: "Authorization Paths"
        detail: "Define access permissions correctly in Spring Security."

  - category: "Infrastructure & Logging"
    items:
      - id: "I01"
        check_point: "Profile Management"
        detail: "Switch settings across dev/stg/prod environments."
      - id: "I02"
        check_point: "Log Traceability"
        detail: "Include Request IDs (MDC) for end-to-end tracing."

2. 提出された設計書
Markdown

Basic Design: Order Cancellation Functionality
1. Interface Definition
Method: GET

Path: /api/v1/order/cancel

Request Parameter: Long orderId

2. Controller Layer Processing (OrderController)
Accept OrderEntity directly as an argument.

Implement the following logic within the controller:

if (order.getStatus().equals("SHIPPED")) { throw new Exception("Already shipped"); }

Call orderRepository.save(order) to update the status.

3. Security
None in particular (anyone who knows the URL can perform the cancellation).

3. 出力形式
以下の形式で回答してください。

不備の指摘: チェックリストのID(C01など)を添えて、修正が必要な箇所を挙げてください。

結果

### 不備の指摘

#### Presentation Layer
- **C01**: `@RestController` vs `@Controller`の選択  
  `OrderController`で`@RestController`を使用すべきです。GETメソッドのため、ビューを返すのではなくAPIレスポンスを返す設計です。

- **C02**: DTOの利用  
  `OrderEntity`を直接コントローラーで受け取る設計は避けるべきです。リクエストパラメータをバリデーション可能なDTOにマッピングし、ビジネスロジックで使用してください。

- **C03**: バリデーションのローカライゼーション  
  `orderId`パラメータに`@Valid`アノテーションがありません。エントリーポイントで形式チェック(例: `@NotNull`, `@Min`)を行うべきです。

#### Business Layer
- **S01**: トランザクションの境界  
  `orderRepository.save()`を呼び出す処理に`@Transactional`アノテーションがありません。データの一貫性を保証するため、トランザクション管理が必要です。

- **S02**: コンストラクタインジェクション  
  コントローラーやサービスクラスでフィールドインジェクション(`@Autowired`)が使用されている可能性があります。テスト可能性を高めるため、コンストラクタインジェクションを優先すべきです。

- **S03**: ステートレスな設計  
  コントローラーやサービスクラスがユーザー固有のステート(例: セッション情報)を保持していないか確認が必要です。Singletonビーンでユーザー固有の情報を保持しないでください。

#### Persistence Layer
- **D03**: コンカレンシークントロール  
  `orderRepository.save()`で更新を行う前に、`@Version`プロパティを利用したオプティミスティックロックを適用する必要があります。複数ユーザーが同時にキャンセルリクエストを送信した場合の競合を防止するためです。

#### Security & Error Handling
- **X01**: グローバル例外処理  
  `throw new Exception("Already shipped")`は具体的な例外クラス(例: `OrderAlreadyShippedException`)を定義し、`@ControllerAdvice`で統一処理を行うべきです。

- **X03**: アクセス権の定義  
  「誰でもURLを知ればキャンセルできる」というセキュリティ設計は問題です。Spring Securityを使用して、認証されたユーザーまたは

結果としてはレビューしてくれているっぽいが何度やっても、中途半端な点でレビューが終了してしまう。
他のモデルClaude Haiku 4.5というモデルでも行ったが、そもそもこちらは出力すらされなかった、、、

気になった点

ナレッジベースに読み込ませている資料の中身はすべて英語で書かなければS3 Vectorのベクトル埋め込みに同期できない。

Amazon Titan Text Embeddings v2は日本語も対応しているはずだが、日本語で記載された資料(admin_user_deactivation.md)を読み込んで同期を行うと以下のように読み込めない形式としてエラーをはいてしまう。

admin_user_deactivation.md

# 基本設計:管理画面・ユーザー凍結

## 1. 認可ルール
- `@PreAuthorize("hasRole('ADMIN')")` をサービスメソッドに付与。

## 2. 処理詳細
- `users.is_active` フラグを `false` に更新。
- 該当ユーザーがログイン中であれば、セッションを強制無効化(SessionRegistryを使用)。

エラー画面1

画像1.jpg

エラー画面2

image.png

今後の方針

・別の埋め込みモデルで日本語の資料を同期できるか調査
・Nova 2 Lite以外でのモデルでのレビュー
・出力のコンテキストが途中で終わってしまうことに対する調査

5
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?