如何重构 JSON/Elasticsearch 响应

我正在使用Olivere v7。


我正在尝试将&(从ElasticSearch调用,返回JSON响应)合并到一个重新排序的结构中,并以该格式提供结果。_id_source


这是我的实际代码:


elasticsearch, err := //actual request to ES using olivere

fmt.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 olivere


type StructuredResponse struct {

    ID             string  `json:"id"`

    Email          string `json:"email"`

    Name           string `json:"name"`

}


var SR []StructuredResponse

for _, 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)

但是我迷路了,我不确定下一步会是什么,或者从这里做什么。


DIEA
浏览 101回答 2
2回答

慕侠2389804

我认为它应该像这样工作:var srs []StructuredResponsefor _, 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

GCT1015

假设 导出了 的字段,则不需要封送处理输出。elasticsearch.Hits.Hitsfor _, hit := range elasticsearch.Hits.Hits {    SR = append(SR, StructuredResponse{ID: hit.ID, Email: hit.Email, Name: Hit.Name})}这将为您提供一个包含一组完整项目 (SR) 的切片。此时,您应该能够将该切片封送为JSON,如果这是您想要做的。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go