티스토리 뷰

go

Go Elasticsearch 예제

까오기 2024. 7. 18. 15:12

Go에서 Elasticsearch에 요청을 보내고 결과를 받기 위해 공식 Elasticsearch Go 클라이언트를 사용할 수 있습니다. 여기서는 Elasticsearch v7 용 Go 클라이언트를 사용하는 예제를 제공합니다.

Directory 생성 

mkdir elasticsearch
cd ./elasticsearch

프로젝트 초기화 

go mod init elasticsearch

Elasticsearch Go 클라이언트 설치

먼저 Elasticsearch Go 클라이언트를 설치합니다. go get 명령어를 사용합니다:

go get github.com/elastic/go-elasticsearch/v7

Elasticsearch 클라이언트를 사용하여 문서 인덱싱 및 검색 예제

다음은 Elasticsearch에 문서를 인덱싱하고 검색하는 간단한 Go 프로그램입니다.

package main

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"log"
	"strings"

	"github.com/elastic/go-elasticsearch/v7"
	"github.com/elastic/go-elasticsearch/v7/esapi"
)

// Document 구조체 정의
type Document struct {
	Title   string `json:"title"`
	Content string `json:"content"`
}

func main() {
	// Elasticsearch 클라이언트 설정
	cfg := elasticsearch.Config{
		Addresses: []string{
			"http://external-elasticsearch:9200", // 외부 Elasticsearch 클러스터의 주소  
		},
	}
	es, err := elasticsearch.NewClient(cfg)
	if err != nil {
		log.Fatalf("Error creating the client: %s", err)
	}

	// 인덱스 할 문서 정의
	doc := Document{
		Title:   "Hello, Elasticsearch!",
		Content: "This is a simple document.",
	}

	// 문서를 JSON으로 변환
	docJSON, err := json.Marshal(doc)
	if err != nil {
		log.Fatalf("Error marshaling the document: %s", err)
	}

	// 문서 인덱싱
	req := esapi.IndexRequest{
		Index:      "test_es_documents",
		DocumentID: "1",
		Body:       bytes.NewReader(docJSON),
		Refresh:    "true",
	}

	res, err := req.Do(context.Background(), es)
	if err != nil {
		log.Fatalf("Error getting response: %s", err)
	}
	defer res.Body.Close()

	if res.IsError() {
		log.Fatalf("Error indexing document ID=%s", req.DocumentID)
	} else {
		fmt.Printf("Indexed document ID=%s\n", req.DocumentID)
	}

	// 문서 검색
	var buf bytes.Buffer
	query := map[string]interface{}{
		"query": map[string]interface{}{
			"match": map[string]interface{}{
				"title": "elasticsearch",
			},
		},
	}
	if err := json.NewEncoder(&buf).Encode(query); err != nil {
		log.Fatalf("Error encoding query: %s", err)
	}

	searchReq := esapi.SearchRequest{
		Index: []string{"test_es_documents"},
		Body:  strings.NewReader(buf.String()),
	}

	searchRes, err := searchReq.Do(context.Background(), es)
	if err != nil {
		log.Fatalf("Error getting response: %s", err)
	}
	defer searchRes.Body.Close()

	if searchRes.IsError() {
		log.Fatalf("Error searching test_es_documents")
	} else {
		var result map[string]interface{}
		if err := json.NewDecoder(searchRes.Body).Decode(&result); err != nil {
			log.Fatalf("Error parsing the response body: %s", err)
		}

		// 검색 결과 출력
		fmt.Printf("Search result: %+v\n", result)
	}
}

결과 

Indexed document ID=1
Search result: map[_shards:map[failed:0 skipped:0 successful:1 total:1] hits:map[hits:[map[_id:1 _index:test_es_documents _score:0.2876821 _source:map[content:This is a simple document. title:Hello, Elasticsearch!] _type:_doc]] max_score:0.2876821 total:map[relation:eq value:1]] timed_out:false took:0]

설명

  1. Elasticsearch 클라이언트 설정: elasticsearch.NewDefaultClient() 함수를 사용하여 기본 설정으로 Elasticsearch 클라이언트를 만듭니다.
  2. 문서 정의: Document 구조체를 정의하고 인덱싱할 문서를 만듭니다.
  3. 문서 인덱싱:
    • docJSON 변수에 문서를 JSON으로 변환합니다.
    • esapi.IndexRequest 구조체를 사용하여 문서 인덱싱 요청을 만듭니다.
    • req.Do 메서드를 호출하여 인덱싱 요청을 수행하고 응답을 처리합니다.
  4. 문서 검색:
    • query 변수에 검색 쿼리를 정의합니다.
    • esapi.SearchRequest 구조체를 사용하여 검색 요청을 만듭니다.
    • searchReq.Do 메서드를 호출하여 검색 요청을 수행하고 응답을 처리합니다.

이 예제는 Elasticsearch에 문서를 인덱싱하고, 그 문서를 검색하는 과정을 보여줍니다. 이를 통해 Elasticsearch Go 클라이언트를 사용하여 데이터를 인덱싱하고 검색하는 방법을 이해할 수 있습니다.

 

출처 : chatGPT

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함