Procházet zdrojové kódy

添加根据ID获取文档

wcc před 1 rokem
rodič
revize
927f3f682c
2 změnil soubory, kde provedl 44 přidání a 0 odebrání
  1. 30 0
      elastic/elasticSim.go
  2. 14 0
      elastic/elastic_test.go

+ 30 - 0
elastic/elasticSim.go

@@ -608,3 +608,33 @@ func (e *Elastic) SaveDocument(index string, data map[string]interface{}) error
 
 	return nil
 }
+
+// GetById 获取单个索引文档
+func (e *Elastic) GetById(index string, id string) (err error, data map[string]interface{}) {
+	client := e.GetEsConn()
+	defer e.DestoryEsConn(client)
+
+	ctx := context.Background()
+
+	// 使用Get方法获取文档
+	getResponse, err := client.Get().
+		Index(index).
+		Id(id).
+		Do(ctx)
+	if err != nil {
+		// 处理错误
+		return err, nil
+	}
+
+	if !getResponse.Found {
+		// 文档存在,返回文档数据
+		return errors.New("Document not found"), nil // 文档不存在,返回错误
+	}
+
+	if err := json.Unmarshal(getResponse.Source, &data); err != nil {
+		// 处理解码错误
+		return err, nil
+	}
+
+	return nil, data
+}

+ 14 - 0
elastic/elastic_test.go

@@ -178,3 +178,17 @@ func TestElastic_SaveDocument(t *testing.T) {
 	err := esClinet.SaveDocument("bidding", data)
 	assert.Equal(t, nil, err)
 }
+
+func TestElastic_GetById(t *testing.T) {
+	esClinet = Elastic{
+		S_esurl:  "http://127.0.0.1:19805",
+		I_size:   2,
+		Username: "es_all",
+		Password: "TopJkO2E_d1x",
+	}
+	esClinet.InitElasticSize()
+
+	err, doc := esClinet.GetById("bidding", "59ed510d40d2d9bbe85dd221")
+	assert.Equal(t, nil, err)
+	fmt.Println("doc", doc)
+}