简体   繁体   中英

How to map the resultset of elasticsearch query with Java High Level Rest Client API?

I am using ES 7.2. Below is a sample query result from ES. It has two fields STATUS and SERVICE_ID:

{{
  "took" : 4,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 106,
      "relation" : "eq"
    },
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "myindex",
        "_type" : "_doc",
        "_id" : "ENXDrWsBF759w7WDGxK4",
        "_score" : 1.0,
        "_source" : {
          "STATUS" : "10",
          "SERVICE_ID" : "916"
        }
      },
      {
        "_index" : "myindex",
        "_type" : "_doc",
        "_id" : "EdXDrWsBF759w7WDGxK4",
        "_score" : 1.0,
        "_source" : {
          "STATUS" : "10",
          "SERVICE_ID" : "916"
        }
      }
    ]
  }
}

I want to map it to my Java Bean "MyBean" below:

public class MyBean {

  String SERVICE_ID;
  String STATUS;

public String getSERVICE_ID() {
    return SERVICE_ID;
}
public void setSERVICE_ID(String sERVICE_ID) {
    SERVICE_ID = sERVICE_ID;
}
public String getSTATUS() {
    return STATUS;
}
public void setSTATUS(String sTATUS) {
    STATUS = sTATUS;
}
}

I have tried the mapping below by using ObjectMapper's of jackson library but it had the following exception:

        try {
                    SearchResponse searchResponse1 = client.search(searchRequest, RequestOptions.DEFAULT);
            ObjectMapper mapper = new ObjectMapper();
            java.util.List<MyBean> lst = new ArrayList<MyBean>();
            for(SearchHit hit : searchResponse1.getHits().getHits()) {
//here below, i have the exception
                MyBean s = mapper.readValue(hit.getSourceAsString(), MyBean.class);
                lst.add(s);
            } 

The below is the exception:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "STATUS" (class MyBean), not marked as ignorable (2 known properties: "status",  "service_ID")
 at [Source: (String)"{"STATUS":"11"}"; line: 1, column: 12] (through reference chain: MyBean["STATUS"])

Do you have any idea?

How about this?

public class MyBean {
    private String status;
    private String name;
 
    @JsonProperty("SERVICE_ID")
    public void setServiceId(String serviceId) {
        this.serviceId = serviceId;
    }
 
    @JsonProperty("SERVICE_ID")
    public String getServiceId() {
        return serviceId;
    }

    @JsonProperty("STATUS")
    public void setStatus(String status) {
        this.status = status;
    }
 
    @JsonProperty("STATUS")
    public String getStatus() {
        return status;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM