semantic-ranker-default-003과 같은 Vertex AI 순위 지정 모델을 사용하여 애플리케이션 검색 결과 순위를 지정 및 재지정하는 방법을 알아봅니다.
ai.rank() 함수를 사용하여 쿼리와의 관련성을 기반으로 문서에 점수를 매기고 더 나은 쿼리 순서를 위해 순위를 재지정하여 벡터 검색 결과를 개선할 수 있습니다.
Vertex AI Ranking API는 문서 목록을 가져와 지정된 쿼리(검색 문자열)와의 문서 관련성을 기반으로 문서 순위를 지정합니다. ai.rank() 함수를 사용하면 문서가 지정된 쿼리에 얼마나 잘 답변하는지에 대한 점수가 반환됩니다.
이 페이지의 안내를 사용하려면 AlloyDB Omni를 이해하고 생성형 AI 개념에 익숙해야 합니다.
AlloyDB Omni는 ai 스키마를 예약하고 만듭니다.
시작하기 전에
검색 결과 순위를 지정하기 전에 다음을 수행합니다.
- Vertex AI 모델에 대한 사용자 액세스 권한을 구성합니다.
- 최신 버전의
google_ml_integration이 설치되어 있는지 확인합니다.설치된 버전을 확인하려면 다음 명령어를 실행합니다.
SELECT extversion FROM pg_extension WHERE extname = 'google_ml_integration'; extversion ------------ 1.5.2 (1 row)
확장 프로그램이 설치되지 않았거나 설치된 버전이 1.5.2 이전이면 확장 프로그램을 업데이트합니다.
CREATE EXTENSION IF NOT EXISTS google_ml_integration; ALTER EXTENSION google_ml_integration UPDATE;
위 명령어를 실행할 때 문제가 발생하거나 위 명령어를 실행한 후에도 확장 프로그램이 1.5.2 버전으로 업데이트되지 않으면 Google Cloud 지원팀에 문의하세요.
AlloyDB AI 쿼리 엔진 기능을 사용하려면
google_ml_integration.enable_ai_query_engine플래그를on로 설정합니다.- 텍스트 편집기를 사용하여 AlloyDB Omni 설치의
postgresql.conf구성 파일에서 다음 플래그를 설정합니다.google_ml_integration.enable_ai_query_engine = on
postgresql.conf파일을 저장한 후 변경사항을 적용하려면 AlloyDB Omni 서비스를 다시 시작합니다.sudo systemctl restart alloydbomni18
- 텍스트 편집기를 사용하여 AlloyDB Omni 설치의
Discovery Engine API 사용 설정
<p>To use ranking models, you must enable the Discovery Engine API.<br>
Replace <code><var>PROJECT_ID</var></code> with your
Google Cloud project ID and <code><var>PROJECT_NUMBER</var></code>
with your corresponding project number.</p>
<pre class="prettyprint lang-terminal">
# Enable Discovery Engine API
gcloud services enable discoveryengine.googleapis.com --project=<var>PROJECT_ID</var>
gcloud projects add-iam-policy-binding <var>PROJECT_ID</var> \
--member="serviceAccount:service-<var>PROJECT_NUMBER</var>@iam.gserviceaccount.com" \
--role="roles/discoveryengine.viewer"
</pre>
<p>Model registration for ranking isn't required for Vertex AI models.
You can use the Vertex AI model name as the
<code>model_id</code>, which is shown in the following example.
</p>
<pre class="prettyprint lang-sh">
SELECT index, score
FROM
ai.rank(
model_id => 'semantic-ranker-default-003',
search_string => 'Affordable family-friendly vacation spots in Southeast Asia?',
documents =>
ARRAY[
'Luxury resorts in South Korea',
'Family vacation packages for Vietnam: Ha Long Bay and Hoi An',
'Budget-friendly beaches in Thailand perfect for families',
'A backpacker guide to solo travel in India'])
</pre>
<p>A common use case for the semantic ranker is to rerank the results returned
by vector search for better query ordering. The following example shows how to
use the semantic ranking model for this use case. The example retrieves an
initial result set for the query <code>personal fitness
equipment</code> using vector search. These results are then re-ranked to
return the top five results.
</p>
<pre class="prettyprint lang-sh">
WITH initial_ranking AS (
SELECT id, description, ROW_NUMBER() OVER () AS ref_number
FROM product
ORDER BY
embedding <=> google_ml.embedding(
'gemini-embedding-001', 'personal fitness equipment')::vector
LIMIT 10
), reranked_results AS (
SELECT index, score
FROM ai.rank(
model_id => 'semantic-ranker-default-003',
search_string => 'personal fitness equipment',
documents => (SELECT ARRAY_AGG(description ORDER BY ref_number) FROM initial_ranking),
top_n => 5)
)
SELECT id, description
FROM initial_ranking, reranked_results
WHERE initial_ranking.ref_number = reranked_results.index
ORDER BY reranked_results.score DESC;
</pre>
<p>For a list of available models and use cases, see <a href="/generative-ai-app-builder/docs/ranking#models">Supported models</a>.</p>
Vertex AI와 통합 및 확장 프로그램 설치
자세한 내용은 클라우드 기반 모델을 쿼리하도록 AlloyDB Omni 설치 구성을 참고하세요.
필요한 역할
Discovery Engine의 순위 모델을 사용하는 데 필요한 권한을 얻으려면 관리자에게 AlloyDB Omni 서비스 계정에 your project에 대한 Discovery Engine 뷰어 (roles/discoveryengine.viewer) Identity and Access Management (IAM) 역할을 부여해 달라고 요청하세요. 역할 부여에 대한 자세한 내용은 프로젝트, 폴더, 조직에 대한 액세스 관리를 참조하세요.
커스텀 역할이나 다른 사전 정의된 역할을 통해 필요한 권한을 얻을 수도 있습니다.
검색 결과 순위 지정
다음 SQL 쿼리에서는 검색 결과 순위를 지정하는 방법을 보여줍니다.
SELECT
ai.rank(
model_id => 'MODEL_ID',
search_string => 'SEARCH_STRING',
documents => ARRAY['DOCUMENT_1', 'DOCUMENT_2', 'DOCUMENT_3']);
다음을 바꿉니다.
| 매개변수 | 설명 |
|---|---|
MODEL_ID |
개발자가 정의한 모델 엔드포인트의 고유 ID입니다. |
SEARCH_STRING |
레코드 순위가 지정되는 검색 문자열입니다. |
DOCUMENTS |
순위를 지정하려는 고유한 텍스트 문자열의 배열입니다. |
지원되는 Vertex AI 순위 모델 목록은 지원되는 모델을 참조하세요.
예시
Vertex AI 순위 모델을 사용하여 검색 결과 순위를 지정하려면 다음 쿼리를 실행합니다.
SELECT index, score
FROM
ai.rank(
model_id => 'semantic-ranker-default-003',
search_string => 'AlloyDB is a PostgreSQL compatible AI database that is ready for production.',
documents =>
ARRAY[
'Alloys are made from combination of metals',
'The best enterprise-ready PostgreSQL database.',
'You can feel the heat in Alloy apartments.']);
응답은 각 문서와 검색어와의 관련성에 따른 점수를 보여주는 테이블입니다. 다음은 샘플 응답입니다.
index | score
-------+------------
2 | 0.33
1 | 0.28
3 | 0.16
(3 rows)
리뷰 설명 목록이 포함된 AlloyDB Omni 데이터베이스가 임베딩으로 변환된다고 가정해 보겠습니다. 다음 샘플 코드 스니펫에서는 순위 모델을 사용하여 쿼리에 대한 리뷰 설명 의미 유사성을 기반으로 순위가 가장 높은 제품의 이름을 검색하는 방법을 보여줍니다.
WITH initial_ranking AS (
SELECT product_id, name, review, review_id, ROW_NUMBER() OVER () AS ref_number
FROM user_reviews
ORDER BY
review_desc_embedding <=> google_ml.embedding(
'gemini-embedding-001', 'good desserts')::vector
LIMIT 10
), reranked_results AS (
SELECT index, score
FROM
ai.rank(
model_id => 'semantic-ranker-512',
search_string => 'good desserts',
documents => (SELECT ARRAY_AGG(review ORDER BY ref_number) FROM initial_ranking),
top_n => 5)
)
SELECT product_id, name
FROM initial_ranking, reranked_results
WHERE initial_ranking.ref_number = reranked_results.index
ORDER BY reranked_results.score DESC;