🗄️
데이터베이스
Elasticsearch
엘라스틱서치
분산 검색/분석 엔진. 로그 분석, 전문 검색에 사용. ELK 스택의 핵심.
엘라스틱서치
분산 검색/분석 엔진. 로그 분석, 전문 검색에 사용. ELK 스택의 핵심.
Elasticsearch는 Apache Lucene 기반의 분산형 오픈소스 검색 및 분석 엔진입니다. RESTful API를 통해 대용량 데이터를 실시간으로 저장, 검색, 분석할 수 있으며, 전문 검색(Full-text Search), 로그 분석, 시계열 데이터 분석에 널리 사용됩니다.
PUT /products
{
"settings": {
"number_of_shards": 3,
"number_of_replicas": 1,
"analysis": {
"analyzer": {
"korean": {
"type": "custom",
"tokenizer": "nori_tokenizer"
}
}
}
},
"mappings": {
"properties": {
"name": {
"type": "text",
"analyzer": "korean",
"fields": {
"keyword": { "type": "keyword" }
}
},
"description": { "type": "text", "analyzer": "korean" },
"price": { "type": "integer" },
"category": { "type": "keyword" },
"created_at": { "type": "date" },
"tags": { "type": "keyword" }
}
}
}
# 문서 색인
POST /products/_doc
{
"name": "맥북 프로 16인치",
"description": "M3 Pro 칩 탑재 고성능 노트북",
"price": 3490000,
"category": "electronics",
"tags": ["laptop", "apple", "premium"],
"created_at": "2024-01-15"
}
# ID 지정 색인
PUT /products/_doc/1
{
"name": "아이패드 프로",
"description": "M2 칩, Liquid Retina XDR 디스플레이",
"price": 1729000,
"category": "electronics",
"tags": ["tablet", "apple"]
}
# 문서 조회
GET /products/_doc/1
# Match Query (전문 검색)
GET /products/_search
{
"query": {
"match": {
"description": "고성능 노트북"
}
}
}
# Bool Query (복합 조건)
GET /products/_search
{
"query": {
"bool": {
"must": [
{ "match": { "description": "노트북" } }
],
"filter": [
{ "term": { "category": "electronics" } },
{ "range": { "price": { "gte": 1000000, "lte": 3000000 } } }
],
"should": [
{ "term": { "tags": "premium" } }
],
"minimum_should_match": 1
}
},
"sort": [
{ "price": "asc" },
"_score"
],
"from": 0,
"size": 10
}
GET /products/_search
{
"size": 0,
"aggs": {
"category_stats": {
"terms": {
"field": "category",
"size": 10
},
"aggs": {
"avg_price": { "avg": { "field": "price" } },
"max_price": { "max": { "field": "price" } },
"price_ranges": {
"range": {
"field": "price",
"ranges": [
{ "to": 1000000 },
{ "from": 1000000, "to": 2000000 },
{ "from": 2000000 }
]
}
}
}
},
"daily_sales": {
"date_histogram": {
"field": "created_at",
"calendar_interval": "day"
}
}
}
}
from elasticsearch import Elasticsearch
es = Elasticsearch(['http://localhost:9200'])
# 문서 색인
doc = {
'name': '맥북 에어',
'price': 1690000,
'category': 'electronics'
}
es.index(index='products', id=1, document=doc)
# 검색
query = {
'bool': {
'must': [{'match': {'name': '맥북'}}],
'filter': [{'range': {'price': {'lte': 2000000}}}]
}
}
results = es.search(index='products', query=query)
for hit in results['hits']['hits']:
print(f"Score: {hit['_score']}, Name: {hit['_source']['name']}")
# Bulk 색인 (대량 데이터)
from elasticsearch.helpers import bulk
actions = [
{'_index': 'products', '_id': i, '_source': {'name': f'Product {i}'}}
for i in range(1000)
]
bulk(es, actions)