Elasticsearch: Python으로 첫 번째 검색 쿼리 작성하기
개요
Elasticsearch 소개
Elasticsearch는 텍스트 검색의 업계 표준인 BM25를 시작으로 다양한 검색 기술을 제공합니다. 또한 AI 모델 기반의 시맨틱 검색을 제공하여 컨텍스트와 의도에 따라 결과를 개선합니다.
Elasticsearch는 Python, Rust, Java, JavaScript 및 기타 언어를 포함한 여러 프로그래밍 언어에 대한 공식 클라이언트를 제공합니다. 이러한 클라이언트는 인덱싱, 검색 및 클러스터 관리를 위한 완전한 API 지원을 제공합니다. 성능에 최적화되어 있으며 Elasticsearch 릴리스와 함께 최신 상태로 유지되어 호환성과 보안을 보장합니다.
시작하기
이 예제에서는 몇 개의 문서를 색인하고 Python을 사용해 쿼리 작업을 합니다. 이 가이드가 끝나면 백엔드 애플리케이션을 Elasticsearch에 연결하여 쿼리에 응답하는 방법을 배우게 됩니다.
Elastic Cloud 프로젝트 생성
14일 체험판으로 시작해 보세요. 이동하여 계정을 생성한 후 아래 단계에 따라 첫 번째 Elasticsearch Serverless 프로젝트를 시작하는 방법을 알아보고 Elasticsearch를 선택합니다.
그런 다음 General purpose를 만들고 My Project 와 같은 이름을 지정한 후 생성합니다.

첫 번째 Elasticsearch 인덱스를 생성하고, 이를 my-index로 명명하겠습니다. 내 인덱스 생성을 선택합니다.
첫 번째 인덱스를 생성했습니다! 다음으로 애플리케이션이 Elasticsearch와 통신할 수 있도록 API 키를 생성합니다. 원하는 언어를 선택합니다. 이 예제에서는 Python을 활용합니다.
Elasticsearch로 데이터 시작하기
터미널에서 pip를 사용하여 다음과 같이 Elasticsearch 클라이언트를 설치합니다.
pip install elasticsearch
오른쪽 상단 모서리에서 API 키를 복사하여 프로젝트 URL과 함께 클라이언트의 구성에 추가합니다. 이미 인덱스에 대한 매핑을 생성할 수 있으며, 여기에는 'text'라는 이름의 텍스트 필드만 있을 것입니다.
from elasticsearch import Elasticsearch
client = Elasticsearch(
"https://my-project-bff300.es.us-east-1.aws.elastic.cloud:443",
api_key="YOUR-API-KEY"
)
index_name = "my-index"
mappings = {
"properties": {
"text": {
"type": "text"
}
}
}
mapping_response = client.indices.put_mapping(index=index_name, body=mappings)
print(mapping_response)
그런 다음 마지막으로 대량 요청을 사용하여 Elasticsearch로 데이터를 전송할 수 있습니다. _bulk 요청을 사용하여 3개의 문서를 색인해 보겠습니다. 수백에서 수십억 개의 문서를 색인할 때도 대량 요청을 사용해야 한다는 것을 잊지 마세요. 이는 Elasticsearch에서 대량의 문서를 색인할 때 선호되는 선택입니다.
docs = [
{
"text": "Yellowstone National Park is one of the largest national parks in the United States. It ranges from the Wyoming to Montana and Idaho, and contains an area of 2,219,791 acress across three different states. Its most famous for hosting the geyser Old Faithful and is centered on the Yellowstone Caldera, the largest super volcano on the American continent. Yellowstone is host to hundreds of species of animal, many of which are endangered or threatened. Most notably, it contains free-ranging herds of bison and elk, alongside bears, cougars and wolves. The national park receives over 4.5 million visitors annually and is a UNESCO World Heritage Site."
},
{
"text": "Yosemite National Park is a United States National Park, covering over 750,000 acres of land in California. A UNESCO World Heritage Site, the park is best known for its granite cliffs, waterfalls and giant sequoia trees. Yosemite hosts over four million visitors in most years, with a peak of five million visitors in 2016. The park is home to a diverse range of wildlife, including mule deer, black bears, and the endangered Sierra Nevada bighorn sheep. The park has 1,200 square miles of wilderness, and is a popular destination for rock climbers, with over 3,000 feet of vertical granite to climb. Its most famous and cliff is the El Capitan, a 3,000 feet monolith along its tallest face."
},
{
"text": "Rocky Mountain National Park is one of the most popular national parks in the United States. It receives over 4.5 million visitors annually, and is known for its mountainous terrain, including Longs Peak, which is the highest peak in the park. The park is home to a variety of wildlife, including elk, mule deer, moose, and bighorn sheep. The park is also home to a variety of ecosystems, including montane, subalpine, and alpine tundra. The park is a popular destination for hiking, camping, and wildlife viewing, and is a UNESCO World Heritage Site."
}
]
bulk_response = helpers.bulk(client, docs, index=index_name)
print(bulk_response)
Elasticsearch에서 문서를 볼 수 있습니다.
Elasticsearch로 작업하기
쿼리 작성
쿼리를 정의하고 다음 검색 요청을 실행하는 새 스크립트(예: search.py)를 생성합니다.
FROM my-index
| WHERE MATCH(text, "yosemite")
| LIMIT 5
다음과 같이 client.esql.query 내에 이 쿼리를 추가합니다.
from elasticsearch import Elasticsearch
client = Elasticsearch(
"https://my-project-bff307.es.us-east-1.aws.elastic.cloud:443",
api_key="YOUR-API-KEY"
)
# Execute the search query
response = client.esql.query(
query="""
FROM my-index
| WHERE MATCH(text, "yosemite")
| LIMIT 5
""",
format="csv"
)
print(response)
다음과 같이 결과를 확인하세요.
"요세미티 국립공원은 미국 국립공원으로, 캘리포니아주에 위치하며 75만 에이커 이상의 면적을 차지하고 있습니다. 유네스코 세계유산으로 등재된 이 공원은 화강암 절벽, 폭포, 거대한 세쿼이아 나무로 유명합니다. 거의 매년 400만 명 이상의 관광객이 방문하며, 2016년에는 500만 명으로 정점을 찍었습니다. 공원에는 노새사슴, 흑곰, 멸종위기종인 시에라 네바다 큰뿔양 등 다양한 야생동물이 서식하고 있습니다. 1,200제곱마일의 황야가 있으며, 3,000피트가 넘는 수직 화강암이 있어 암벽 등반가에게 인기 있는 여행지입니다. 가장 유명한 절벽은 엘 캐피탄으로, 가장 높은 면이 3,000피트인 거대한 바위입니다.
이제 클라이언트를 사용하여 Flask, Django 등과 같은 모든 Python 백엔드에서 Elasticsearch를 쿼리할 준비가 되었습니다. 더 자세히 알아보려면 Elasticsearch Python 클라이언트 설명서를 확인하세요.
다음 단계
Elastic Cloud를 사용하여 데이터에 대한 시맨틱 검색을 설정하는 데 시간을 내주셔서 감사합니다. Elastic과 함께 하는 여정을 시작하면서 환경 전체에 배포할 때 사용자로서 관리해야 하는 몇 가지 운영, 보안 및 데이터 구성 요소를 이해해야 합니다.
시작할 준비가 되셨나요? Elastic Cloud에서 14일 무료 체험판을 시작하거나 Search AI 101에서 15분 분량의 실습 학습을 해보세요.