opensearch crud操作
#开源 #go #crud #opensearch

介绍:

OpenSearch是一种开源搜索和分析引擎,为存储,索引和搜索数据提供了强大的平台。作为GO开发人员,您可以利用OpenSearch GO SDK以编程方式执行CRUD(创建,读取,更新,删除)操作。在本文中,我们将探讨如何使用GO和OpenSearch GO SDK在OpenSearch中执行CRUD操作。

在我的上一个示例中,我通过卷曲解释了卷曲操作。
View Article

先决条件:

要跟随本文中的示例,您需要在系统上安装并可以访问OpenSearch Cluster。

在docker-compose文件中运行开放式搜索群

创建docker-compose.yml文件

version: '3'
services:
  opensearch-node1: # This is also the hostname of the container within the Docker network (i.e. https://opensearch-node1/)
    image: opensearchproject/opensearch:latest # Specifying the latest available image - modify if you want a specific version
    container_name: opensearch-node1
    environment:
      - cluster.name=opensearch-cluster # Name the cluster
      - node.name=opensearch-node1 # Name the node that will run in this container
      - discovery.seed_hosts=opensearch-node1,opensearch-node2 # Nodes to look for when discovering the cluster
      # - cluster.initial_cluster_manager_nodes=opensearch-node1,opensearch-node2 # Nodes eligible to serve as cluster manager
      - bootstrap.memory_lock=true # Disable JVM heap memory swapping
      - "OPENSEARCH_JAVA_OPTS=-Xms512m -Xmx512m" # Set min and max JVM heap sizes to at least 50% of system RAM
    ulimits:
      memlock:
        soft: -1 # Set memlock to unlimited (no soft or hard limit)
        hard: -1
      nofile:
        soft: 65536 # Maximum number of open files for the opensearch user - set to at least 65536
        hard: 65536
    volumes:
      - opensearch-data1:/usr/share/opensearch/data # Creates volume called opensearch-data1 and mounts it to the container
    ports:
      - 9200:9200 # REST API
      - 9600:9600 # Performance Analyzer
    networks:
      - opensearch-net # All of the containers will join the same Docker bridge network

  opensearch-dashboards:
    image: opensearchproject/opensearch-dashboards:latest # Make sure the version of opensearch-dashboards matches the version of opensearch installed on other nodes
    container_name: opensearch-dashboards
    ports:
      - 5601:5601 # Map host port 5601 to container port 5601
    expose:
      - "5601" # Expose port 5601 for web access to OpenSearch Dashboards
    environment:
      OPENSEARCH_HOSTS: '["https://opensearch-node1:9200"]' # Define the OpenSearch nodes that OpenSearch Dashboards will query
    networks:
      - opensearch-net

volumes:
  opensearch-data1:
  opensearch-data2:

networks:
  opensearch-net:

验证此群集正在运行:

  • 在终端中运行命令

curl https://localhost:9200/_cat/indices -ku 'admin:admin'

  • 打开仪表板http://0.0.0.0:5601/的URL使用用户名访问它:admin和密码:admin

在仪表板中运行命令

opensearh-dashboards dev tool

opensearh-dashboards dev commands

设置OpenSearch GO SDK:

在潜入CRUD操作之前,我们需要设置OpenSearch GO SDK。官方的OpenSearch GO SDK(也称为OpenSearch-Go)提供了一种简单而直观的方式,可以使用GO与OpenSearch进行交互。要安装SDK,请使用以下命令:

go get github.com/opensearch-project/opensearch-go/v2

执行CRUD操作:

现在我们已经设置了OpenSearch GO SDK,让我们潜入CRUD操作:
您也可以在此处引用repo中的代码:https://github.com/ankitmalikg2/opensearch-crud

创建索引:

要在OpenSearch中创建索引,我们需要初始化客户端并使用CreateIndex API。这是一个例子:

package main

import (
    "crypto/tls"
    "fmt"
    "net/http"

    opensearch "github.com/opensearch-project/opensearch-go/v2"
)

func main() {
    // Replace with your OpenSearch cluster details
    endpoint := "https://localhost:9200"
    username := "admin" // Leave empty if not using authentication
    password := "admin" // Leave empty if not using authentication

    // Create a client
    client, err := opensearch.NewClient(opensearch.Config{
        Addresses: []string{endpoint},
        Username:  username,
        Password:  password,
        Transport: &http.Transport{
            TLSClientConfig: &tls.Config{
                InsecureSkipVerify: true,
            },
        },
    })
    if err != nil {
        fmt.Println("Error creating OpenSearch client:", err)
        return
    }

    // Create an index
    indexName := "dev-article"
    err = createIndex(client, indexName)
    if err != nil {
        fmt.Println("Error creating index:", err)
        return
    }
    fmt.Println("Index created:", indexName)
}

func createIndex(client *opensearch.Client, indexName string) error {

    _, err := client.Indices.Create(indexName)

    if err != nil {
        return err
    }

    return nil
}

输出:

Index created: dev-article

索引或添加文档:

要在OpenSearch中索引文档,我们可以使用索引API。这是一个例子:

package main

import (
    "crypto/tls"
    "fmt"
    "net/http"

    "github.com/opensearch-project/opensearch-go/opensearchutil"
    opensearch "github.com/opensearch-project/opensearch-go/v2"
)

func main() {
    // Replace with your OpenSearch cluster details
    endpoint := "https://localhost:9200"
    username := "admin" // Leave empty if not using authentication
    password := "admin" // Leave empty if not using authentication

    // Create a client
    client, err := opensearch.NewClient(opensearch.Config{
        Addresses: []string{endpoint},
        Username:  username,
        Password:  password,
        Transport: &http.Transport{
            TLSClientConfig: &tls.Config{
                InsecureSkipVerify: true,
            },
        },
    })
    if err != nil {
        fmt.Println("Error creating OpenSearch client:", err)
        return
    }

    // Index a document
    indexName := "dev-article"
    documentID := "1"
    document := map[string]interface{}{
        "title":   "Getting Started with OpenSearch",
        "content": "OpenSearch is a powerful open-source search and analytics engine...",
    }
    err = indexDocument(client, indexName, documentID, document)
    if err != nil {
        fmt.Println("Error indexing document:", err)
        return
    }
    fmt.Println("Document indexed:", documentID)
}

func indexDocument(client *opensearch.Client, indexName string, documentID string, document map[string]interface{}) error {

    _, err := client.Create(indexName, documentID, opensearchutil.NewJSONReader(document))

    return err
}

输出:

Document indexed: 1

检索文件:

要从OpenSearch检索文档,我们可以使用GET API。这是一个例子:

package main

import (
    "context"
    "fmt"
    opensearch "github.com/opensearch-project/opensearch-go"
    "github.com/opensearch-project/opensearch-go/opensearchapi"
)

func main() {
    // Replace with your OpenSearch cluster details
    endpoint := "http://localhost:9200"
    username := "" // Leave empty if not using authentication
    password := "" // Leave empty if not using authentication

    // Create a client
    client, err := opensearch.NewClient(opensearch.Config{
        Addresses: []string{endpoint},
        Username:  username,
        Password:  password,
    })
    if err != nil {
        fmt.Println("Error creating OpenSearch client:", err)
        return
    }

    // Retrieve a document
    indexName := "dev-article"
    documentID := "1"
    retrievedDocument, err := getDocument(client, indexName, documentID)
    if err != nil {
        fmt.Println("Error retrieving document:", err)
        return
    }
    fmt.Println("Retrieved Document:", retrievedDocument)
}

func getDocument(client *opensearch.Client, indexName string, documentID string) (map[string]interface{}, error) {
    getRequest := opensearchapi.GetRequest{
        Index: indexName,
        ID:    documentID,
    }

    response, err := client.Get(&getRequest)
    if err != nil {
        return nil, err
    }

    document := response.Source

    return document, nil
}

输出:

Retrieved Document: map[_id:1 _index:dev-article _primary_term:1 _seq_no:0 _source:map[content:OpenSearch is a powerful open-source search and analytics engine... title:Getting Started with OpenSearch] _version:1 found:true]

更新文档:

要在OpenSearch中更新文档,我们可以使用更新API。这是一个例子:

package main

import (
    "crypto/tls"
    "fmt"
    "net/http"

    opensearch "github.com/opensearch-project/opensearch-go/v2"
    "github.com/opensearch-project/opensearch-go/v2/opensearchutil"
)

func main() {
    // Replace with your OpenSearch cluster details
    endpoint := "https://localhost:9200"
    username := "admin" // Leave empty if not using authentication
    password := "admin" // Leave empty if not using authentication

    // Create a client
    client, err := opensearch.NewClient(opensearch.Config{
        Addresses: []string{endpoint},
        Username:  username,
        Password:  password,
        Transport: &http.Transport{
            TLSClientConfig: &tls.Config{
                InsecureSkipVerify: true,
            },
        },
    })
    if err != nil {
        fmt.Println("Error creating OpenSearch client:", err)
        return
    }

    // Update a document
    indexName := "dev-article"
    documentID := "1"
    updatedFields := map[string]interface{}{
        "doc": map[string]interface{}{
            "content": "Updated api content-- OpenSearch is a powerful open-source search",
        },
    }

    err = updateDocument(client, indexName, documentID, updatedFields)
    if err != nil {
        fmt.Println("Error updating document:", err)
        return
    }
    fmt.Println("Document updated:", documentID)
}

func updateDocument(client *opensearch.Client, indexName string, documentID string, updatedFields map[string]interface{}) error {
    res, err := client.Update(indexName, documentID, opensearchutil.NewJSONReader(updatedFields))

    if err != nil {
        return err
    }
    defer res.Body.Close()

    if res.IsError() {
        return fmt.Errorf("update document request failed: %s", res.String())
    }

    return nil
}

输出:

Document updated: 1

更新后读取输出:

Retrieved Document: map[_id:1 _index:dev-article _primary_term:1 _seq_no:1 _source:map[content:Updated api content-- OpenSearch is a powerful open-source search title:Getting Started with OpenSearch] _version:2 found:true]

删除文档:

要从OpenSearch删除文档,我们可以使用删除API。这是一个例子:

package main

import (
    "crypto/tls"
    "fmt"
    "net/http"

    opensearch "github.com/opensearch-project/opensearch-go/v2"
)

func main() {
    // Replace with your OpenSearch cluster details
    endpoint := "https://localhost:9200"
    username := "admin" // Leave empty if not using authentication
    password := "admin" // Leave empty if not using authentication

    // Create a client
    client, err := opensearch.NewClient(opensearch.Config{
        Addresses: []string{endpoint},
        Username:  username,
        Password:  password,
        Transport: &http.Transport{
            TLSClientConfig: &tls.Config{
                InsecureSkipVerify: true,
            },
        },
    })
    if err != nil {
        fmt.Println("Error creating OpenSearch client:", err)
        return
    }

    // Delete a document
    indexName := "dev-article"
    documentID := "1"
    err = deleteDocument(client, indexName, documentID)
    if err != nil {
        fmt.Println("Error deleting document:", err)
        return
    }
    fmt.Println("Document deleted:", documentID)
}

func deleteDocument(client *opensearch.Client, indexName string, documentID string) error {

    _, err := client.Delete(indexName, documentID)
    if err != nil {
        return err
    }

    return nil
}

输出:

Document deleted: 1

结论:

在本文中,我们探讨了如何使用GO和OpenSearch GO SDK在OpenSearch中执行CRUD操作。我们介绍了创建索引,索引文档,检索文档,更新文档并删除文档的步骤。通过利用OpenSearch GO SDK,GO开发人员可以通过编程方式与Opensearch进行交互,并构建强大的搜索和分析应用程序。请记住,根据您的特定OpenSearch集群配置和要求自定义代码示例。愉快的索引和搜索搜索和搜索!