001/* 002 * (C) Copyright 2016 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * Kevin Leturc 018 */ 019package org.nuxeo.elasticsearch.core; 020 021import java.io.Serializable; 022import java.util.Arrays; 023import java.util.HashMap; 024import java.util.List; 025import java.util.Map; 026import java.util.stream.Collectors; 027 028import org.elasticsearch.search.SearchHit; 029import org.nuxeo.ecm.core.query.sql.NXQL; 030import org.nuxeo.ecm.core.schema.types.Type; 031import org.nuxeo.ecm.core.schema.types.primitives.DateType; 032 033/** 034 * Converter used to convert a {@link SearchHit} to a {@link Map}<{@link String}, {@link Serializable}>. 035 * 036 * @since 8.4 037 */ 038public class EsSearchHitConverter { 039 040 private final Map<String, Type> selectFieldsAndTypes; 041 042 private final Map<String, Serializable> emptyRow; 043 044 public EsSearchHitConverter(Map<String, Type> selectFieldsAndTypes) { 045 this.selectFieldsAndTypes = selectFieldsAndTypes; 046 this.emptyRow = buildEmptyRow(selectFieldsAndTypes); 047 } 048 049 private static Map<String, Serializable> buildEmptyRow(Map<String, Type> selectFieldsAndTypes) { 050 Map<String, Serializable> emptyRow = new HashMap<>(selectFieldsAndTypes.size()); 051 for (String fieldName : selectFieldsAndTypes.keySet()) { 052 emptyRow.put(fieldName, null); 053 } 054 return emptyRow; 055 } 056 057 public List<Map<String, Serializable>> convert(SearchHit... hits) { 058 return Arrays.stream(hits).map(this::convert).collect(Collectors.toList()); 059 } 060 061 public Map<String, Serializable> convert(SearchHit hit) { 062 Map<String, Serializable> row = new HashMap<>(emptyRow); 063 hit.getSourceAsMap().forEach((name, value) -> { 064 // type conversion 065 if (value instanceof String) { 066 Type type = selectFieldsAndTypes.get(name); 067 if (type instanceof DateType) { 068 // convert back to calendar 069 value = type.decode(((String) value)); 070 } 071 } 072 row.put(name, (Serializable) value); 073 }); 074 if (selectFieldsAndTypes.containsKey(NXQL.ECM_FULLTEXT_SCORE)) { 075 row.put(NXQL.ECM_FULLTEXT_SCORE, (double) hit.getScore()); 076 } 077 return row; 078 } 079 080}