728x90
반응형
Elasticsearch 실행
- elasticsearch.bat 로 elasticsearch 실행
- 보안 설정 해제
- 로컬 환경의 보다 편리한 테스트를 위해 아이디/비밀번호 가 필요한 보안 설정 해제
- /elasticsearch/config 폴더의 elasticsearch.yml 파일의 xpack.security.enabled를 false로 변경
Elasticsearch 객체 생성 및 index 생성
- indices : index의 복수형으로 물리적인 저장 공간을 의미
- title, url, published, timestamp를 field로 하는 index 생성
from elasticsearch import Elasticsearch
es = Elasticsearch("http://localhost:9200")
INDEX_NAME = "new_articles"
def create_index():
if not es.indices.exists(index=INDEX_NAME):
es.indices.create(index=INDEX_NAME, body={
"settings":{"number_of_shards":1},
"mappings":{
"properties": {
"title": {"type":"text"},
"url": {"type":"keyword"},
"publised": {"type":"date"},
"timestamp":{"type":"date"},
}
}
})
Elasticsearch에 데이터를 저장
from datetime import datetime
from backend.services.newsapi import get_articles
from elastic.es_client import es, INDEX_NAME
def index_articles():
articles = get_articles()["articles"]
for article in articles:
doc = {
"title":article["title"],
"url":article["url"],
"publised":article["publishedAt"],
"timestamp":datetime.now(),
}
es.index(index=INDEX_NAME, body=doc)
return {"message":"Ariticle indexed", "count": len(articles)}
Elasticsearch 데이터 저장 및 쿼리 검색 추가
- /index_articles : newsapi를 통해 가져온 기사를 elasticsearch에 저장
- /search : elasticsearch 에서 key가 포함된 기사를 검색
# news_main.py에 추가
from elastic.article_to_es import index_articles
from elastic.es_client import es, INDEX_NAME
@app.get('/index_articles')
def indexing_articles():
return index_articles()
@app.get('/search')
def search_articles(key:str):
query = {
"query": {
"match": {
"title": key
}
}
}
result = es.search(index=INDEX_NAME, body=query)
return {"result":result["hits"]["hits"]}
'ML_DL > MUJAKJUNG (무작정 시리즈)' 카테고리의 다른 글
[LangChain] 시작하기 (0) | 2025.03.19 |
---|---|
Elasticsearch, Airflow 활용하기 - 3. Airflow 환경설정 (0) | 2025.03.04 |
Elasticsearch, Airflow 활용하기 - 1. 환경설정 (0) | 2025.03.03 |
이미지 분류 모델 작성하기 (feat. wandb) (0) | 2025.02.19 |
프로젝트 업그레이드 1탄 - 프로젝트 생성 (0) | 2025.02.06 |