///* // * Copyright 2014-2016 the original author or authors. // * // * Licensed under the Apache License, Version 2.0 (the "License"); // * you may not use this file except in compliance with the License. // * You may obtain a copy of the License at // * // * http://www.apache.org/licenses/LICENSE-2.0 // * // * Unless required by applicable law or agreed to in writing, software // * distributed under the License is distributed on an "AS IS" BASIS, // * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // * See the License for the specific language governing permissions and // * limitations under the License. // */ //package com.walker.support.es.impl; // // //import com.fasterxml.jackson.core.JsonEncoding; //import com.fasterxml.jackson.core.JsonFactory; //import com.fasterxml.jackson.core.JsonGenerator; //import com.walker.infrastructure.utils.StringUtils; //import com.xinyuan.core.persistence.search.so.BaseSearchObject; //import org.apache.commons.lang.StringUtils; //import org.elasticsearch.action.get.GetResponse; //import org.elasticsearch.action.get.MultiGetItemResponse; //import org.elasticsearch.action.get.MultiGetResponse; //import org.elasticsearch.action.search.SearchResponse; //import org.elasticsearch.common.document.DocumentField; //import org.elasticsearch.common.text.Text; //import org.elasticsearch.search.SearchHit; //import org.elasticsearch.search.fetch.subphase.highlight.HighlightField; //import org.slf4j.Logger; //import org.slf4j.LoggerFactory; //import org.springframework.data.domain.Pageable; //import org.springframework.data.elasticsearch.ElasticsearchException; //import org.springframework.data.elasticsearch.annotations.Document; //import org.springframework.data.elasticsearch.annotations.ScriptedField; //import org.springframework.data.elasticsearch.core.AbstractResultMapper; //import org.springframework.data.elasticsearch.core.DefaultEntityMapper; //import org.springframework.data.elasticsearch.core.EntityMapper; //import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage; //import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl; //import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentEntity; //import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentProperty; //import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext; //import org.springframework.data.mapping.PersistentProperty; //import org.springframework.data.mapping.context.MappingContext; //import org.springframework.stereotype.Component; // //import java.io.ByteArrayOutputStream; //import java.io.IOException; //import java.nio.charset.Charset; //import java.util.*; // ///** // * 扩展结果转换对象,增加高亮摘要字段内容处理 // * // * @author Artur Konczak // * @author Petar Tahchiev // * @author Young Gu // * @author Oliver Gierke // */ //@Component //public class DefaultResultMapper extends AbstractResultMapper { // private static final Logger logger = LoggerFactory.getLogger(DefaultResultMapper.class); // // private MappingContext, ElasticsearchPersistentProperty> mappingContext; // // public DefaultResultMapper(MappingContext, ElasticsearchPersistentProperty> mappingContext) { // super(new DefaultEntityMapper(mappingContext)); // this.mappingContext = mappingContext; // } // // public DefaultResultMapper(EntityMapper entityMapper) { // super(entityMapper); // } // public DefaultResultMapper() { // this(new SimpleElasticsearchMappingContext()); // } // // public DefaultResultMapper( // MappingContext, ElasticsearchPersistentProperty> mappingContext, // EntityMapper entityMapper) { // super(entityMapper); // this.mappingContext = mappingContext; // } // // @Override // public AggregatedPage mapResults(SearchResponse response, Class clazz, Pageable pageable) { // //logger.info("highlight -> {}", ToStringBuilder.reflectionToString(response, ToStringStyle.MULTI_LINE_STYLE)); // long totalHits = response.getHits().getTotalHits(); // List results = new ArrayList<>(); // for (SearchHit hit : response.getHits()) { // if (hit != null) { // T result; // if (StringUtils.isNotBlank(hit.getSourceAsString())) { // result = mapEntity(hit.getSourceAsString(), clazz); // } else { // result = mapEntity(hit.getFields().values(), clazz); // } // setPersistentEntityId(result, hit.getId(), clazz); // populateScriptFields(result, hit); // // // 处理高亮内容 // this.handleHighlight(hit, result); // results.add(result); // } // } // // return new AggregatedPageImpl<>(results, pageable, totalHits, response.getAggregations()); // } // // private void populateScriptFields(T result, SearchHit hit) { // if (hit.getFields() != null && !hit.getFields().isEmpty() && result != null) { // for (java.lang.reflect.Field field : result.getClass().getDeclaredFields()) { // ScriptedField scriptedField = field.getAnnotation(ScriptedField.class); // if (scriptedField != null) { // String name = scriptedField.name().isEmpty() ? field.getName() : scriptedField.name(); // DocumentField searchHitField = hit.getFields().get(name); // if (searchHitField != null) { // field.setAccessible(true); // try { // field.set(result, searchHitField.getValue()); // } catch (IllegalArgumentException e) { // throw new ElasticsearchException("failed to set scripted field: " + name + " with value: " + searchHitField.getValue(), e); // } catch (IllegalAccessException e) { // throw new ElasticsearchException("failed to access scripted field: " + name, e); // } // } // } // } // } // } // // // private T mapEntity(Collection values, Class clazz) { // return mapEntity(buildJSONFromFields(values), clazz); // } // // private String buildJSONFromFields(Collection values) { // JsonFactory nodeFactory = new JsonFactory(); // try { // ByteArrayOutputStream stream = new ByteArrayOutputStream(); // JsonGenerator generator = nodeFactory.createGenerator(stream, JsonEncoding.UTF8); // generator.writeStartObject(); // for (DocumentField value : values) { // if (value.getValues().size() > 1) { // generator.writeArrayFieldStart(value.getName()); // for (Object val : value.getValues()) { // generator.writeObject(val); // } // generator.writeEndArray(); // } else { // generator.writeObjectField(value.getName(), value.getValue()); // } // } // generator.writeEndObject(); // generator.flush(); // return new String(stream.toByteArray(), Charset.forName("UTF-8")); // } catch (IOException e) { // logger.error(e.getMessage(), e); // return null; // } // } // // @Override // public T mapResult(GetResponse response, Class clazz) { // T result = mapEntity(response.getSourceAsString(), clazz); // if (result != null) { // setPersistentEntityId(result, response.getId(), clazz); // } // return result; // } // // @Override // public LinkedList mapResults(MultiGetResponse responses, Class clazz) { // LinkedList list = new LinkedList<>(); // for (MultiGetItemResponse response : responses.getResponses()) { // if (!response.isFailed() && response.getResponse().isExists()) { // T result = mapEntity(response.getResponse().getSourceAsString(), clazz); // setPersistentEntityId(result, response.getResponse().getId(), clazz); // list.add(result); // } // } // return list; // } // // private void setPersistentEntityId(T result, String id, Class clazz) { // // if (mappingContext != null && clazz.isAnnotationPresent(Document.class)) { // // ElasticsearchPersistentEntity persistentEntity = mappingContext.getPersistentEntity(clazz); // PersistentProperty idProperty = persistentEntity.getIdProperty(); // // // Only deal with String because ES generated Ids are strings ! // if (idProperty != null && idProperty.getType().isAssignableFrom(String.class)) { // persistentEntity.getPropertyAccessor(result).setProperty(idProperty, id); // } // } // } // // /** // * 处理高亮显示内容,将高亮数据放入最外层的highlightMap对象 // * // * @param hit 命中的查询结果 // * @param obj 待返回的查询结果对象 // */ // private void handleHighlight(SearchHit hit, Object obj) { // //logger.info("highlight -> {}", ToStringBuilder.reflectionToString(hit.highlightFields().keySet(), ToStringStyle.MULTI_LINE_STYLE)); // if (obj instanceof BaseSearchObject) { // BaseSearchObject searchPo = (BaseSearchObject) obj; // if (hit != null) { // Map highlightFieldMap = hit.getHighlightFields(); // if (highlightFieldMap != null) { // for (Map.Entry entry : highlightFieldMap.entrySet()) { // HighlightField highlightField = entry.getValue(); // Text[] texts = highlightField.fragments(); // if (texts != null) { // for (Text text : texts) { // if (text != null) { // searchPo.putHighlight(entry.getKey(), text.toString().replaceAll("\\s+", " ").trim()); // } // } // } // } // } // } // } // } //}