package test; import java.net.InetAddress; import java.util.Map; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.client.Client; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.elasticsearch.search.highlight.HighlightField; public class R1 { public static void main(String[] args) throws Exception { Settings settings = Settings.settingsBuilder().build(); Client client = TransportClient.builder().settings(settings).build() .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("xxx.xxx.xxx.xxx"),9300)); SearchResponse response = client.prepareSearch("index") .setTypes("type") .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .setQuery(QueryBuilders.matchQuery("text","设置")) .addHighlightedField("text") .setHighlighterPreTags("<font color='red'>") .setHighlighterPostTags("</font>") .setSize(2) .get(); SearchHits hits = response.getHits(); System.out.println("总量"+hits.getTotalHits()); SearchHit[] hitArray = hits.hits(); for (SearchHit hit : hitArray) { Map<String, HighlightField> highlightFields = hit.getHighlightFields(); //打印高亮显示内容 for (Map.Entry<String, HighlightField> entry : highlightFields.entrySet()) { System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); } } client.close(); } }