代码之家  ›  专栏  ›  技术社区  ›  Ankita Gupta

转到elasticsearch获取所有文档

  •  0
  • Ankita Gupta  · 技术社区  · 3 年前

    我正在尝试使用go elasticsearch从ES获取所有数据。

    "github.com/elastic/go-elasticsearch/v8"
    "github.com/elastic/go-elasticsearch/v8/esapi"
    

    到目前为止,我已经编写了以下代码:

    var r map[string]interface{}    
    cfg := elasticsearch.Config{
        Addresses: []string{
            fmt.Sprint(viper.Get("ELASTICSEARCH_URL")),
        },
    }
    
    es, err := elasticsearch.NewClient(cfg)
    if err != nil {
        log.Fatalf("Error creating the client: %s", err)
    }
    res, err := es.Search(
        es.Search.WithContext(context.Background()),
        es.Search.WithIndex(index_name),
        es.Search.WithTrackTotalHits(true),
        es.Search.WithPretty(),
        es.Search.WithFrom(0),
        es.Search.WithSize(1000),
    )
    
    if err != nil {
        log.Printf("Error getting response: %s", err)
    }
    defer res.Body.Close()
    
    if res.IsError() {
        var e map[string]interface{}
        if err := json.NewDecoder(res.Body).Decode(&e); err != nil {
            log.Printf("Error parsing the response body: %s", err)
        } else {
            // Print the response status and error information.
            log.Printf("[%s] %s: %s",
                res.Status(),
                e["error"].(map[string]interface{})["type"],
                e["error"].(map[string]interface{})["reason"],
            )
        }
    }
    
    if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
        log.Printf("Error parsing the response body: %s", err)
    }
    // Print the response status, number of results, and request duration.
    log.Printf(
        "[%s] %d hits; took: %dms",
        res.Status(),
        int(r["hits"].(map[string]interface{})["total"].(map[string]interface{})["value"].(float64)),
        int(r["took"].(float64)),
    )
    fmt.Println("length", len(r["hits"].(map[string]interface{})["hits"].([]interface{})))
    domain := fmt.Sprint(viper.Get("DOMAIN"))
    for _, hit := range r["hits"].(map[string]interface{})["hits"].([]interface{}) {
        doc := hit.(map[string]interface{})
        source := doc["_source"]
    }
    

    0 回复  |  直到 3 年前
        1
  •  1
  •   Sahil Gupta    3 年前
    • Scrolling 搜索结果。
    • 除非需要,否则不要滚动,因为滚动操作成本高昂