我想使用Spring Data Elasticsearch从ES获取聚合,代码如下(在服务中):
public SearchHits<Document> getDocumentMetadata() {
Query query = new NativeSearchQueryBuilder()
.withAggregations(terms("documents-aggr").field("type.keyword"))
.withQuery(QueryBuilders.matchAllQuery())
.withMaxResults(0)
.build();
return elasticsearchOperations.search(query, Document.class);
}
在控制器中,代码看起来像这样:
@GetMapping("documents")
public SearchHits<Document> getDocumentsMetadata() {
return documentService.getDocumentMetadata();
}
Document
类非常简单,看起来像这样:
@Data
@NoArgsConstructor
@AllArgsConstructor
@org.springframework.data.elasticsearch.annotations.Document(indexName = "rtk-documents")
public class Document {
private List<String> authors;
private String title;
private DocumentType type;
}
当我向这个端点发送请求时,我得到:
{
"timestamp": "2022-04-26T10:52:28.653+00:00",
"status": 500,
"error": "Internal Server Error",
"path": "/documents"
}
内部异常看起来像这样:
2022-04-26 12:52:28.648 ERROR 277610 --- [io-10210-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class org.springframework.data.elasticsearch.core.clients.elasticsearch7.ElasticsearchAggregations]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.springframework.data.elasticsearch.core.clients.elasticsearch7.ElasticsearchAggregations and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.data.elasticsearch.core.SearchHitsImpl["aggregations"])] with root cause
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.springframework.data.elasticsearch.core.clients.elasticsearch7.ElasticsearchAggregations and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.data.elasticsearch.core.SearchHitsImpl["aggregations"])
at
...
使用的版本:
- spring-boot-starter-web,spring-data-elasticsearch:2.6.7
我想知道如何使控制器序列化ES的答案并将其发送到客户端。我搜索了这个问题,但没有找到任何与我的问题相关的答案。
1条答案
按热度按时间hgqdbh6s1#
您可以使用
ElasticsearchClient
来获取实现JsonpSerializable
的对象,而不是使用ElasticsearchOperations
。你可以使用
JsonpUtils
类来序列化为json。例如: