fix(es): ES 集群 7.7.1 与高阶客户端 7.17 不兼容,电量消息/换纸日志查询降级低阶 RestClient

生产两个 ES 集群均为 7.7.1:elasticsearch-java 7.17 的 vendor Content-Type
(application/vnd.elasticsearch+json; compatible-with=7) 被 406 拒绝,
且其 X-Elastic-Product 响应头校验(7.14 引入)在 7.7.1 上无法通过。
ElectricityMessageEsGatewayImpl 与 PaperUseLogEsGatewayImpl 改用低阶
RestClient 直连(application/json、无产品头校验),查询语义不变。
修复REQ-20260921-0007上线后 tools/call 406 冒烟失败。
This commit is contained in:
my_local_kimi_dev2
2026-09-22 11:21:46 +08:00
parent 10d618dac2
commit 6be5169217
4 changed files with 184 additions and 156 deletions
@@ -22,6 +22,8 @@ import java.util.Arrays;
* 双集群 ES 客户端:cloud=云集群、local=本地化集群(老系统 Dictionary.LocalEsDate 分界)。
* 低阶 RestClient 也注册为 bean(destroyMethod=close 随容器关闭);
* 高阶 ElasticsearchClient 包装同一 RestClient,关闭 client 即关闭底层连接。
* 注意:生产两个集群均为 ES 7.7.1,高阶客户端(7.17)的 vendor Content-Type 与
* X-Elastic-Product 校验与 7.7.1 不兼容(406),业务查询一律注入低阶 RestClient bean。
*/
@Configuration
public class EsClientConfig {
@@ -1,16 +1,12 @@
package me.iiv.agent.es;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.FieldValue;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.json.JsonData;
import jakarta.json.JsonNumber;
import jakarta.json.JsonObject;
import jakarta.json.JsonString;
import jakarta.json.JsonValue;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@@ -22,8 +18,12 @@ import java.util.ArrayList;
import java.util.List;
/**
* electricitymessage_yyyyMM ES 查询实现(elasticsearch-java 7.17 强类型 API),
* 只注入 esLocal 客户端(索引只在本地集群,不走 esCloud)。
* electricitymessage_yyyyMM ES 查询实现。
* 降级原因:生产 ES 集群为 7.7.1,elasticsearch-java 7.17 高阶客户端(ElasticsearchClient)
* 请求自带 vendor Content-Type(application/vnd.elasticsearch+json; compatible-with=7)被
* 7.7.1 以 406 Not Acceptable 拒绝,且 7.17 客户端校验响应 X-Elastic-Product 头(7.14 才引入),
* 7.7.1 没有,二次兼容也过不了;故改用低阶 RestClient(只发普通 application/json、无产品头校验)。
* 只注入 esLocalRestClient(索引只在本地集群,不走 esCloud)。
* 查询口径对齐老 BatteryAnalyseController.batteryAnalyseList 但修掉其坑:
* snCode 用 match_phrase(老代码 matchQuery 经 standard analyzer 会把 AB-123 切成 ab/123 误配)、
* messageType 不传不加 term(老代码默认值 0 会把"不传"歧义成"电量")、createTime 闭区间 range、
@@ -37,47 +37,50 @@ public class ElectricityMessageEsGatewayImpl implements ElectricityMessageEsGate
private static final DateTimeFormatter TIME_FORMATTER =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(BUSINESS_ZONE);
private final ElasticsearchClient localClient;
private final RestClient localRestClient;
private final ObjectMapper mapper = new ObjectMapper();
public ElectricityMessageEsGatewayImpl(@Qualifier("esLocalClient") ElasticsearchClient localClient) {
this.localClient = localClient;
public ElectricityMessageEsGatewayImpl(@Qualifier("esLocalRestClient") RestClient localRestClient) {
this.localRestClient = localRestClient;
}
@Override
public Result search(String index, String snCode, Integer messageType,
String startTime, String endTime, int from, int size) {
List<Query> filters = new ArrayList<>();
ArrayNode filters = mapper.createArrayNode();
// 老代码 snCode 字符串走 matchQuery(BaseSearchSupportImpl2 type=0 非数值分支),
// standard analyzer 会把 AB-123 切成 ab/123 造成误配;改用 match_phrase 精确短语
filters.add(Query.of(q -> q.matchPhrase(m -> m.field("snCode").query(snCode))));
filters.addObject().putObject("match_phrase").putObject("snCode").put("query", snCode);
if (messageType != null) {
filters.add(Query.of(q -> q.term(t -> t.field("messageType")
.value(FieldValue.of(messageType.longValue())))));
filters.addObject().putObject("term").putObject("messageType").put("value", messageType);
}
// 老代码 rangeQuery from(start,true).to(end,true),闭区间
filters.add(Query.of(q -> q.range(r -> r.field("createTime")
.gte(JsonData.of(startTime)).lte(JsonData.of(endTime)))));
ObjectNode range = filters.addObject().putObject("range").putObject("createTime");
range.put("gte", startTime).put("lte", endTime);
ObjectNode body = mapper.createObjectNode();
body.put("from", from).put("size", size);
body.put("track_total_hits", true);
ObjectNode bool = body.putObject("query").putObject("bool");
bool.set("filter", filters);
body.putArray("sort").addObject().putObject("createTime").put("order", "asc");
try {
SearchResponse<JsonData> response = localClient.search(s -> s
.index(index)
.from(from)
.size(size)
.trackTotalHits(t -> t.enabled(true))
.query(q -> q.bool(b -> b.filter(filters)))
.sort(so -> so.field(f -> f.field("createTime").order(SortOrder.Asc))),
JsonData.class);
Request req = new Request("POST", "/" + index + "/_search");
// setJsonEntity 自动带 Content-Type: application/json(无 vendor 头)
req.setJsonEntity(mapper.writeValueAsString(body));
Response resp = localRestClient.performRequest(req);
JsonNode root = mapper.readTree(resp.getEntity().getContent());
List<Record> records = new ArrayList<>();
for (Hit<JsonData> hit : response.hits().hits()) {
JsonData source = hit.source();
for (JsonNode hit : root.at("/hits/hits")) {
JsonNode source = hit.get("_source");
if (source == null) {
continue;
}
JsonObject obj = source.toJson().asJsonObject();
records.add(new Record(createTimeText(obj.get("createTime")),
integerValue(obj.get("messageType")),
integerValue(obj.get("value"))));
records.add(new Record(createTimeText(source.get("createTime")),
integerValue(source.get("messageType")),
integerValue(source.get("value"))));
}
return new Result(response.hits().total().value(), records);
return new Result(root.at("/hits/total/value").asLong(), records);
} catch (IOException | RuntimeException e) {
throw new IllegalStateException("ES 查询电量消息记录失败: " + e.getMessage(), e);
}
@@ -87,21 +90,20 @@ public class ElectricityMessageEsGatewayImpl implements ElectricityMessageEsGate
* createTime 在索引里可能是 yyyy-MM-dd HH:mm:ss 文本(老 range 直接传字符串可证 ES 接受该格式),
* 也可能是 epoch 毫秒数;两种形态都归一为 yyyy-MM-dd HH:mm:ss 文本输出。
*/
private static String createTimeText(JsonValue value) {
if (value == null || value.getValueType() == JsonValue.ValueType.NULL) {
private static String createTimeText(JsonNode value) {
if (value == null || value.isNull()) {
return null;
}
if (value instanceof JsonString) {
return ((JsonString) value).getString();
if (value.isTextual()) {
return value.asText();
}
if (value instanceof JsonNumber) {
return TIME_FORMATTER.format(Instant.ofEpochMilli(((JsonNumber) value).longValue()));
if (value.isNumber()) {
return TIME_FORMATTER.format(Instant.ofEpochMilli(value.longValue()));
}
return null;
}
private static Integer integerValue(JsonValue value) {
return value != null && value.getValueType() == JsonValue.ValueType.NUMBER
? ((JsonNumber) value).intValue() : null;
private static Integer integerValue(JsonNode value) {
return value != null && value.isNumber() ? value.intValue() : null;
}
}
@@ -1,19 +1,24 @@
package me.iiv.agent.es;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.FieldValue;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.json.JsonData;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* paperuselog ES 查询实现(elasticsearch-java 7.17 强类型 API)。
* paperuselog ES 查询实现。
* 降级原因:生产 ES 集群为 7.7.1,elasticsearch-java 7.17 高阶客户端(ElasticsearchClient)
* 请求自带 vendor Content-Type(application/vnd.elasticsearch+json; compatible-with=7)被
* 7.7.1 以 406 Not Acceptable 拒绝,且 7.17 客户端校验响应 X-Elastic-Product 头(7.14 才引入),
* 7.7.1 没有,二次兼容也过不了;故改用低阶 RestClient(只发普通 application/json、无产品头校验)。
* 查询口径对齐老 MonthlyStatisticsController.getMonthlyStatisticsMap:
* term districtId/gender、range createTime [gte,lte](含边界)、deviceType 用 match(老代码字符串参数走 match),
* positionMode 厕位=positionsId>0、厕墙=positionsId=0。
@@ -25,31 +30,37 @@ public class PaperUseLogEsGatewayImpl implements PaperUseLogEsGateway {
/** rfid terms 聚合去重上限,超出部分不计入 */
private static final int RFID_TERMS_SIZE = 10000;
private final ElasticsearchClient cloudClient;
private final ElasticsearchClient localClient;
private final RestClient cloudRestClient;
private final RestClient localRestClient;
private final ObjectMapper mapper = new ObjectMapper();
public PaperUseLogEsGatewayImpl(@Qualifier("esCloudClient") ElasticsearchClient cloudClient,
@Qualifier("esLocalClient") ElasticsearchClient localClient) {
this.cloudClient = cloudClient;
this.localClient = localClient;
public PaperUseLogEsGatewayImpl(@Qualifier("esCloudRestClient") RestClient cloudRestClient,
@Qualifier("esLocalRestClient") RestClient localRestClient) {
this.cloudRestClient = cloudRestClient;
this.localRestClient = localRestClient;
}
@Override
public long distinctRfidCount(String index, boolean localCluster, Long districtId, Integer gender,
Long fromMillis, Long toMillis, Integer deviceType, String positionMode) {
List<Query> filters = baseFilters(districtId, gender, fromMillis, toMillis, deviceType, positionMode);
ArrayNode filters = baseFilters(districtId, gender, fromMillis, toMillis, deviceType, positionMode);
// 上纸(2)+撤纸(4) 合并后 rfid 去重(老 :302-342)
filters.add(Query.of(q -> q.terms(t -> t.field("state")
.terms(tt -> tt.value(List.of(FieldValue.of(2), FieldValue.of(4)))))));
ArrayNode stateTerms = filters.addObject().putObject("terms").putObject("state").putArray("terms");
stateTerms.add(2).add(4);
try {
return client(localCluster).search(s -> s
.index(index)
.size(0)
.trackTotalHits(t -> t.enabled(true))
.query(q -> q.bool(b -> b.filter(filters)))
.aggregations("rfids", a -> a.terms(t -> t.field("rfid").size(RFID_TERMS_SIZE))),
Void.class)
.aggregations().get("rfids").sterms().buckets().array().size();
ObjectNode body = mapper.createObjectNode();
body.put("size", 0);
body.put("track_total_hits", false);
ObjectNode bool = body.putObject("query").putObject("bool");
bool.set("filter", filters);
body.putObject("aggs").putObject("rfids").putObject("terms")
.put("field", "rfid").put("size", RFID_TERMS_SIZE);
Request req = new Request("POST", "/" + index + "/_search");
req.setJsonEntity(mapper.writeValueAsString(body));
Response resp = client(localCluster).performRequest(req);
JsonNode root = mapper.readTree(resp.getEntity().getContent());
return root.at("/aggregations/rfids/buckets").size();
} catch (IOException | RuntimeException e) {
throw new IllegalStateException("ES 查询换纸 rfid 去重失败: " + e.getMessage(), e);
}
@@ -58,40 +69,47 @@ public class PaperUseLogEsGatewayImpl implements PaperUseLogEsGateway {
@Override
public long countState2(String index, boolean localCluster, Long districtId, Integer gender,
Long fromMillis, Long toMillis, Integer deviceType, String positionMode) {
List<Query> filters = baseFilters(districtId, gender, fromMillis, toMillis, deviceType, positionMode);
filters.add(Query.of(q -> q.term(t -> t.field("state").value(FieldValue.of(2)))));
ArrayNode filters = baseFilters(districtId, gender, fromMillis, toMillis, deviceType, positionMode);
filters.addObject().putObject("term").putObject("state").put("value", 2);
try {
return client(localCluster).count(c -> c.index(index)
.query(q -> q.bool(b -> b.filter(filters)))).count();
ObjectNode body = mapper.createObjectNode();
ObjectNode bool = body.putObject("query").putObject("bool");
bool.set("filter", filters);
Request req = new Request("POST", "/" + index + "/_count");
req.setJsonEntity(mapper.writeValueAsString(body));
Response resp = client(localCluster).performRequest(req);
JsonNode root = mapper.readTree(resp.getEntity().getContent());
return root.get("count").asLong();
} catch (IOException | RuntimeException e) {
throw new IllegalStateException("ES 查询换纸上纸记录数失败: " + e.getMessage(), e);
}
}
private List<Query> baseFilters(Long districtId, Integer gender, Long fromMillis, Long toMillis,
Integer deviceType, String positionMode) {
List<Query> filters = new ArrayList<>();
filters.add(Query.of(q -> q.term(t -> t.field("districtId").value(FieldValue.of(districtId)))));
filters.add(Query.of(q -> q.term(t -> t.field("gender").value(FieldValue.of(gender)))));
private ArrayNode baseFilters(Long districtId, Integer gender, Long fromMillis, Long toMillis,
Integer deviceType, String positionMode) {
ArrayNode filters = mapper.createArrayNode();
filters.addObject().putObject("term").putObject("districtId").put("value", districtId);
filters.addObject().putObject("term").putObject("gender").put("value", gender);
// createTime 为 epoch 毫秒;含边界(老 rangeQuery from/to 均 inclusive)
filters.add(Query.of(q -> q.range(r -> r.field("createTime")
.gte(JsonData.of(fromMillis)).lte(JsonData.of(toMillis)))));
ObjectNode range = filters.addObject().putObject("range").putObject("createTime");
range.put("gte", fromMillis).put("lte", toMillis);
if (deviceType != null) {
// 老代码 deviceType 为字符串参数走 matchQuery(BaseSearchSupportImpl2 type=0 非数值分支)
filters.add(Query.of(q -> q.match(m -> m.field("deviceType")
.query(FieldValue.of(String.valueOf(deviceType))))));
filters.addObject().putObject("match").putObject("deviceType")
.put("query", String.valueOf(deviceType));
}
if (StringUtils.hasText(positionMode)) {
if ("position".equals(positionMode)) {
filters.add(Query.of(q -> q.range(r -> r.field("positionsId").gt(JsonData.of(0)))));
filters.addObject().putObject("range").putObject("positionsId").put("gt", 0);
} else {
filters.add(Query.of(q -> q.term(t -> t.field("positionsId").value(FieldValue.of(0)))));
filters.addObject().putObject("term").putObject("positionsId").put("value", 0);
}
}
return filters;
}
private ElasticsearchClient client(boolean localCluster) {
return localCluster ? localClient : cloudClient;
private RestClient client(boolean localCluster) {
return localCluster ? localRestClient : cloudRestClient;
}
}