본문 바로가기

카테고리 없음

Elasticsearch 사용하기

 

우선 설치하기 

pip install elasticsearch

 

from elasticsearch import Elasticsearch, helpers
import json

# Elasticsearch 클라이언트 설정
es = Elasticsearch([{'host': 'localhost', 'port': 9200}])

# 인덱스 이름 설정
index_name = 'products'

# 인덱스 생성 (존재하지 않을 경우)
if not es.indices.exists(index=index_name):
    es.indices.create(index=index_name, body={
        'mappings': {
            'properties': {
                'name': {'type': 'text'},
                'price': {'type': 'integer'}

            }
        }
    })

 

  • Elasticsearch 클라이언트 설정:
    • Elasticsearch 객체를 사용하여 localhost:9200에서 실행 중인 Elasticsearch 인스턴스에 연결합니다.
  • 인덱스 생성:
    • es.indices.exists를 사용하여 인덱스가 존재하는지 확인합니다.
    • 인덱스가 존재하지 않는 경우 es.indices.create를 사용하여 인덱스를 생성합니다.
    • 인덱스 매핑은 데이터 필드(name, price)의 타입을 정의합니다.

 

elastic_transport.ConnectionError: Connection error caused by: ConnectionError(Connection error caused by: NewConnectionError(<urllib3.connection.HTTPConnection object at 0xffffab4ded00>: Failed to establish a new connection: [Errno 111] Connection refused))

 

-> 에러발생 

 

해당 에러는 Elasticsearch 클라이언트가 지정된 호스트 및 포트에 연결하려고 시도했지만 연결할 수 없었음을 나타냅니다. 이 에러는 다음과 같은 여러 가지 원인에 의해 발생할 수 있습니다:

  1. Elasticsearch 서버가 실행 중이지 않음:
    • Elasticsearch 서버가 실행 중인지 확인하십시오. 서버가 실행 중이지 않으면 클라이언트가 연결할 수 없습니다.

Elasticsearch 서버 실행 확인:

  • 먼저 Elasticsearch 서버가 실행 중인지 확인합니다. 터미널에서 다음 명령어를 실행하여 확인할 수 있습니다:
  • curl -X GET "localhost:9200/"
    curl: (7) Failed to connect to localhost port 9200: Connection refused
  • 서버를 시작하기
    root@3c0e06e928d4:/buzz# ./bin/elasticsearch
    bash: ./bin/elasticsearch: No such file or directory -> Elasticsearch 실행 파일을 찾을 수 없다는 메시지
  •  

1. Elasticsearch 다운로드 및 설치

먼저 Elasticsearch를 다운로드하고 설치해야 합니다. 최신 버전을 설치하려면 다음 명령어를 사용합니다. Debian 기반의 시스템(예: Ubuntu)에서 Elasticsearch를 설치하는 방법을 설명합니다.

# Elasticsearch 저장소 설정
wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -
sudo apt-get install apt-transport-https
echo "deb https://artifacts.elastic.co/packages/7.x/apt stable main" | sudo tee -a /etc/apt/sources.list.d/elastic-7.x.list
-> deb https://artifacts.elastic.co/packages/7.x/apt stable main

# Elasticsearch 설치
sudo apt-get update
sudo apt-get install elasticsearch
 
맥북의 경우에는 아래와같이 진행 
brew tap elastic/tap
brew install elastic/tap/elasticsearch-full
 
  • Elasticsearch 서비스 시작: Elasticsearch를 설치한 후, 서비스를 시작할 수 있습니다:
    brew services start elastic/tap/elasticsearch-full
  • 설치 확인: Elasticsearch가 정상적으로 설치되었는지 확인합니다. curl을 사용하여 Elasticsearch의 기본 페이지를 확인할 수 있습니다:
    curl http://localhost:9200

2. Elasticsearch 실행

Elasticsearch를 설치한 후, 다음 명령어를 사용하여 Elasticsearch를 시작합니다:

sudo systemctl start elasticsearch
 

Elasticsearch를 시스템 부팅 시 자동으로 시작하도록 설정하려면 다음 명령어를 사용합니다:

sudo systemctl enable elasticsearch

3. Elasticsearch 상태 확인

Elasticsearch가 정상적으로 실행되고 있는지 확인하려면 다음 명령어를 사용합니다:

sudo systemctl status elasticsearch
 
에러발생
-> sudo systemctl status elasticsearch
System has not been booted with systemd as init system (PID 1). Can't operate.
Failed to connect to bus: Host is down
 
 
에러발생
helpers.bulk(es, actions) Data indexed successfully! agent.py:60: ElasticsearchWarning: Elasticsearch built-in security features are not enabled. Without authentication, your cluster could be accessible to anyone. See https://www.elastic.co/guide/en/elasticsearch/reference/7.17/security-minimal-setup.html to enable security. response = es.search(index=index_name, body=query) results : []
 

helpers.bulk가 데이터를 성공적으로 인덱싱했지만, es.search 호출 시 결과가 빈 배열(results : [])로 반환되는 문제를 다루고 계신 것 같습니다. 이 문제를 해결하기 위해 다음 단계를 확인하고 시도해 보세요:

1. 인덱스 확인

먼저, 데이터가 올바르게 인덱싱되었는지 확인합니다. Elasticsearch에 저장된 인덱스 목록을 확인하려면 다음 명령어를 사용하세요:

bash
코드 복사
curl -X GET "localhost:9200/_cat/indices?v"
 
 
 

1. 쿼리와 인덱스 이름 확인

쿼리가 올바르게 작성되었는지, 인덱스 이름이 정확히 지정되었는지 확인하세요. products 인덱스를 대상으로 쿼리하는 예제 코드는 다음과 같습니다:

 

from elasticsearch import Elasticsearch

# Elasticsearch 클라이언트 생성
es = Elasticsearch()

# 검색 쿼리 정의
query = {
    "query": {
        "match_all": {}
    }
}

# 검색 요청
response = es.search(index="products", body=query)
print(response)