elasticsearch 2.x java操作高亮

零度    2018/02/09    总阅读量

高并发、锁   思考   面试   实践   Netty   Linux   Redis   MySQL   Nginx   Maven   Git   ElasticSearch   Spring  
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();
 
	}
 
}


扫描关注:匠心零度

(转载本站文章请注明作者和出处 匠心零度-jiangxinlingdu

Show Disqus Comments

腾讯云:新客户代金券
腾讯云:3年时长最低265元/年
阿里云:ECS云服务器2折起

目录