为了账号安全,请及时绑定邮箱和手机立即绑定

如何重构 JSON/Elasticsearch 响应

如何重构 JSON/Elasticsearch 响应

Go
DIEA 2022-08-01 16:18:10
我正在使用Olivere v7。我正在尝试将&(从ElasticSearch调用,返回JSON响应)合并到一个重新排序的结构中,并以该格式提供结果。_id_source这是我的实际代码:elasticsearch, err := //actual request to ES using oliverefmt.Println(elasticsearch.Hits.Hits)它成功地进行了调用并打印了以下内容:{  "_score": 11.019884,  "_index": "test",  "_type": "_doc",  "_id": "20",  "_seq_no": null,  "_primary_term": null,  "_source": {    "name": "Michael J.",    "age": "22"  }},{  "_score": 11.019884,  "_index": "test",  "_type": "_doc",  "_id": "21",  "_seq_no": null,  "_primary_term": null,  "_source": {    "name": "Michael Jae.",    "age": "18"  }},{  "_score": 11.019884,  "_index": "test",  "_type": "_doc",  "_id": "52",  "_seq_no": null,  "_primary_term": null,  "_source": {    "name": "Michael Jay.",    "age": "69"  }},{  "_score": 11.019884,  "_index": "test",  "_type": "_doc",  "_id": "33",  "_seq_no": null,  "_primary_term": null,  "_source": {    "name": "Michael Jo.",    "age": "25"  }}相反,我只想打印"_id", "name", "age"因此,基于上述相同查询的所需输出将是:{    "id": "20",    "name": "Michael J.",    "age": "22"},{    "id": "21",    "name": "Michael Jae.",    "age": "18"},{    "id": "52",    "name": "Michael Jay.",    "age": "69"},{    "id": "33",    "name": "Michael Jo.",    "age": "25"}我写了这个代码:elasticsearch, err := //actual request to ES using oliveretype StructuredResponse struct {    ID             string  `json:"id"`    Email          string `json:"email"`    Name           string `json:"name"`}var SR []StructuredResponsefor _, hit := range elasticsearch.Hits.Hits {    source, err := json.Marshal(hit.Source)    if err != nil {        panic(err)    }    var SR2 StructuredResponse    err = json.Unmarshal(source, &SR2)    if err != nil {        panic(err)    }    SR = append(SR, SR2)}fmt.Println(SR)但是我迷路了,我不确定下一步会是什么,或者从这里做什么。
查看完整描述

2 回答

?
慕侠2389804

TA贡献1719条经验 获得超6个赞

我认为它应该像这样工作:


var srs []StructuredResponse

for _, hit := range elasticsearch.Hits.Hits {

    var sr StructuredResponse

    if err := json.Unmarshal(hit.Source, &sr); err != nil {

        panic(err)

    }


    sr.ID = hit.Id


    srs = append(srs, sr)

}

该 ID 已在匹配中可用。查看 https://github.com/olivere/elastic/blob/82129300722c28a88207fd5dfed442668d9e264d/search.go#L749


查看完整回答
反对 回复 2022-08-01
?
GCT1015

TA贡献1827条经验 获得超4个赞

假设 导出了 的字段,则不需要封送处理输出。elasticsearch.Hits.Hits


for _, hit := range elasticsearch.Hits.Hits {


    SR = append(SR, StructuredResponse{ID: hit.ID, Email: hit.Email, Name: Hit.Name})

}

这将为您提供一个包含一组完整项目 (SR) 的切片。此时,您应该能够将该切片封送为JSON,如果这是您想要做的。


查看完整回答
反对 回复 2022-08-01
  • 2 回答
  • 0 关注
  • 85 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信