チュートリアル1: プロバイダーによるCKEのセットアップとテスト¶
概要¶
プロバイダー向けに、このチュートリアルでは CKE をセットアップしてテストする方法を説明します。
学習内容¶
このチュートリアルでは、その方法を学びます:
Snowflakeオブジェクトを作成する
データをSnowflakeに読み込み中
ドキュメントをチャンク
Cortex Search Serviceの作成
CKE が正しく動作していることを確認します。
CKE をコンシューマー・アカウントと共有し、テストします。
前提条件¶
このチュートリアルを完了するには、以下の前提条件が必要です。
データベーステーブル、仮想ウェアハウスオブジェクト、Cortex Search Service、およびStreamlitアプリを作成するために必要な権限を付与するロールを持つSnowflakeアカウントとユーザーを持っています。
これらの要件を満たす手順については、 Snowflakeを20分で紹介 をご参照ください。
ステップ1: Snowflakeオブジェクトを作成する¶
最初のステップは、Snowflakeオブジェクトを作成することです。
accountadmin ロールを使用してください。
use role accountadmin;
xsmall_cke_getting_started
という名前のウェアハウスを作成し、インデックスの作成と更新を行います。
create warehouse xsmall_cke_getting_started warehouse_size=xsmall;
cke_owner
という別のロールを作成します。
create role cke_owner;
grant role cke_owner to user admin;
grant usage on warehouse xsmall_cke_getting_started to role cke_owner;
cke_getting_started
という名前のデータベースを作成し、使用します。
grant create database on account to role cke_owner;
use role cke_owner;
create database cke_getting_started;
use database cke_getting_started;
articles
というスキーマを作成し、使用します。
create schema articles;
use schema articles;
ステップ2: データのSnowflakeへの読み込み中¶
次のステップは、データをSnowflakeに読み込み中です。詳細については、 Snowflakeにデータをロード をご参照ください
以下のコード例では、 cke_simple_article
という名前の Snowflake テーブルに、以下の形式でデータを格納しています。
列名 |
型 |
説明 |
---|---|---|
|
|
ドキュメントの一意識別子。これはテーブルのプライマリキーです。 |
|
|
ドキュメントのタイトル。 |
|
|
ドキュメントのソースへの URL リンク。 |
|
|
テキストとして解析されたドキュメントのコンテンツ。これがインデックスされ、検索されるコンテンツです。 |
インデックスを作成したデータセットには、さらにドキュメントのメタデータを含めることができます。以下の例では、 SOURCE_URL
と DOCUMENT_ID
のみを含めていますが、ドキュメントのソースに応じて列を増やすことができます。
簡単なテーブルを作成します。
create or replace table cke_simple_article (
DOCUMENT_ID VARCHAR,
DOCUMENT_TITLE VARCHAR,
SOURCE_URL VARCHAR,
text VARCHAR
);
そのテーブルにサンプルデータを挿入します。
INSERT INTO cke_simple_article (DOCUMENT_ID, DOCUMENT_TITLE, SOURCE_URL, TEXT)
VALUES
('DOC_001', 'Sample Article 1', 'https://example.com/article1', 'This is some sample text for the first article.'),
('DOC_002', 'Sample Article 2', 'https://example.com/article2', 'Another sample text entry for the second article.'),
('DOC_003', 'Sample Article 3', 'https://example.com/article3', 'Yet another piece of text for the third article.');
INSERT INTO cke_simple_article (
DOCUMENT_ID,
DOCUMENT_TITLE,
SOURCE_URL,
text
)
VALUES (
'DOC-GREEN-001',
'The Grand Opening of Greenfield Biosphere',
'https://www.example.com/news/greenfield-biosphere',
'Greenfield Biosphere, nestled in the heart of a once-industrial landscape, opened its doors to the public today amid great fanfare and curiosity. This ambitious environmental initiative, spanning over 120 acres of reclaimed land, has been designed to house thousands of diverse plant species and animals under one vast, transparent dome. Over the past decade, teams of botanists, engineers, and conservationists collaborated intensively to restore the soil quality, implement renewable energy solutions, and establish sustainable water sources. Their efforts have resulted in an oasis that stands as a testament to nature''s resilience and humanity''s unwavering determination to coexist with it.
Upon entering the biosphere, visitors pass through a series of controlled airlocks that maintain precise temperature and humidity levels, ensuring the delicate balance required for each habitat. The moment they step inside, a multitude of colors and scents envelops them. Towering palm trees sway gently, nurtured by a carefully engineered irrigation system that recycles water across various sections of the dome. Exotic butterflies flutter past patches of vibrant orchids, while small reptiles scurry along the edge of meandering pathways. Every detail, from lighting angles to seed selection, has been meticulously planned to promote biodiversity in a space that once lay barren.
Local officials and environmental organizations herald this project as a bold step toward reversing ecological decline. The region had suffered decades of industrial pollution, leaving the soil depleted and wildlife populations on the brink of collapse. Public interest soared once the Greenfield Biosphere project was announced, prompting unprecedented fundraising campaigns and private investments. Citizens volunteered their time to plant seedlings, build composting facilities, and educate children on the importance of ecological stewardship. Now, as thousands explore the dome on opening day, excitement mingles with a sense of responsibility, fueling hope that this initiative can serve as a catalyst for broader restoration efforts.
Beyond merely a tourist attraction, the Greenfield Biosphere plays a crucial role in scientific research. Biologists and ecologists from universities around the globe have established research stations within the dome to study plant migration, cross-pollination, and microclimates. Through advanced sensor networks, they collect data on everything from soil moisture levels to carbon sequestration rates, aiming to develop cutting-edge conservation strategies. Already, preliminary findings suggest that certain flora species exhibit faster growth rates under partial shade, which could help inform future reforestation projects. This research extends to aquatic ecosystems as well, with scientists closely monitoring newly formed ponds and streams for indicators of ecosystem health.
During the grand opening ceremony, Mayor Allison Pierce praised the community for its unwavering dedication to the biosphere''s development. She emphasized how interagency cooperation and community outreach were pivotal in transforming a polluted wasteland into a verdant sanctuary. In her address, she remarked on the significance of involving local youth, who contributed to the design through art projects and educational workshops. According to Mayor Pierce, the next phase of the project will include expanding the biosphere''s capacity for endangered species breeding programs. This could cement the region''s reputation as a global leader in ecological preservation and innovation.
For many, the real highlight of the day was the unveiling of the arboretum wing, a temperature-controlled section featuring ancient tree species that have long faced threats from illegal logging and habitat loss. Towering redwoods, thought to be too large to grow under a dome, stand proudly after years of careful nurturing. Visitors stood in awe as the directors revealed that these trees'' root systems, painstakingly preserved and transplanted, are now thriving in custom-engineered soil mixtures. A sense of reverence filled the air, with many attendees describing the experience as spiritual. The seed of hope planted in the community has visibly taken root.
The venture''s economic impact is another key talking point. Local shops and restaurants anticipate an influx of tourists, and hotels report reservations scheduled months in advance. Construction of new eco-lodges in the surrounding areas is already underway, promising a blend of comfortable accommodations with sustainable building practices. The city council has also approved additional funding to improve roads and public transportation to accommodate the expected rise in visitor numbers. Environmental advocates caution, however, that increased foot traffic could inadvertently strain the biosphere''s delicate ecosystems, calling for balanced planning and continued emphasis on conservation education.
Inside the administrative office, a dedicated operations team monitors real-time data feeds, adjusting temperature, humidity, and nutrient levels to meet each species'' unique needs. Modular solar panels installed around the dome generate sufficient electricity to power the entire facility, showcasing how renewable energy can be integrated seamlessly with large-scale infrastructure. Outside, an innovative wastewater treatment plant recycles greywater for irrigation, minimizing resource consumption. The architects behind the biosphere believe these sustainable technologies can be replicated in other communities looking to rehabilitate degraded land, turning once-polluted sites into living laboratories for environmental stewardship.
While the facility is only in its first phase, future expansions are already on the drawing board. There are plans to introduce a marine habitat zone featuring coral reef tanks that highlight threats to underwater ecosystems. Specially designed walkways will give visitors a close-up view of these aquatic wonders without disturbing the delicate organisms within. Meanwhile, education programs will be expanded to local schools, offering field trips where students can learn about biodiversity, climate change, and sustainable technologies. The hope is that exposure to this living exhibit will inspire the next generation of environmental scientists, engineers, and policymakers.
As dusk settled over the glass dome, a soft, multi-colored illumination replaced the natural daylight, casting enchanting shadows across the tropical foliage. Families strolled slowly along the paths, pausing to read plaques about the origins of each plant or to marvel at the occasional flutter of nocturnal pollinators. Meanwhile, a gentle hum of conversation reverberated in the background, carrying sentiments of astonishment and gratitude. The first day at Greenfield Biosphere ended with a collective realization that, with mindful planning, community collaboration, and respect for nature''s inherent wisdom, it is indeed possible to transform a scarred landscape into a flourishing haven for life and innovation.'
);
ステップ3。ドキュメントをチャンク¶
Cortex Search Serviceを作成する前に、インデックスされるテキストの各「チャンク」が約375語以下のテキストであることを確認する必要があります。これを行うには、 LangChain をインポートする Snowpark UDF を介してチャンクアルゴリズムを適用します。まず、チャンク UDF を作成します。そして、 UDF を cke_simple_article
テーブルに適用し、 cke_simple_article_chunks
テーブルにチャンクを格納します。そして最後に、チャンクが作成されたことを確認します。
以下の例を実行して、Cortex Search Serviceのために記事をパーツにチャンクしてください。この作業には数分かかります。
CREATE OR REPLACE FUNCTION text_chunker(text STRING)
RETURNS TABLE (chunk VARCHAR)
LANGUAGE PYTHON
RUNTIME_VERSION = '3.9'
HANDLER = 'text_chunker'
PACKAGES = ('snowflake-snowpark-python', 'langchain')
AS
$$
from snowflake.snowpark.types import StringType, StructField, StructType
from langchain.text_splitter import RecursiveCharacterTextSplitter
from snowflake.snowpark.files import SnowflakeFile
import logging
import pandas as pd
class text_chunker:
def process(self, text: str):
text_splitter = RecursiveCharacterTextSplitter(
chunk_size = 2000, # Adjust this as needed
chunk_overlap = 300, # Overlap to keep chunks contextual
length_function = len
)
chunks = text_splitter.split_text(text)
df = pd.DataFrame(chunks, columns=['chunk'])
yield from df.itertuples(index=False, name=None)
$$;
以下の例を実行し、ドキュメントをチャンクに分割してインデックスを作成します。
CREATE OR REPLACE TABLE cke_simple_article_chunks AS
SELECT
c.DOCUMENT_ID,
c.DOCUMENT_TITLE,
c.SOURCE_URL,
t.chunk
FROM cke_simple_article AS c, TABLE(text_chunker(CONCAT(c.DOCUMENT_TITLE, '\n', c.TEXT))) AS t;
以下を実行し、チャンクが作成されたことを確認します。
select * from cke_simple_article_chunks;
ステップ4。Cortex Search Serviceの作成¶
ここで、 cke_simple_cortex_search_service
というCortex Search Serviceを構成して、ウェアハウス xsmall_cke_getting_started
で実行し、チャンクされたドキュメントテーブル cke_simple_article_chunks
をリファレンスします。データベースのサイズによっては、このステップの完了にかなりの時間がかかる場合があることに注意してください。
CREATE OR REPLACE CORTEX SEARCH SERVICE cke_simple_cortex_search_service
ON chunk
ATTRIBUTES document_title
WAREHOUSE = xsmall_cke_getting_started
TARGET_LAG = '1 hour'
AS (
SELECT
chunk,
document_title,
source_url
FROM cke_simple_article_chunks
);
ステップ5。CKEをテストする¶
CKE が正しく動作していることを確認するには、Cortex Search Serviceに簡単なクエリを発行します。これにより、サービスがあなたのドキュメントを正しくインデックスし、クエリから関連ドキュメントが返されることを検証します。このクエリは、「The Greenfield Biosphere」という記事の最初のチャンクを、ソース URL へのリンクとともに返すはずです。
select snowflake.cortex.search_preview(
'cke_getting_started.articles.cke_simple_cortex_search_service',
'{ "query": "whats happening with the greenfield biosphere?", "columns": ["chunk","document_title","source_url"] }');