ElasticSearch入门-搜索(java api)

时间:2024-01-03 23:46:56

ElasticSearch入门-搜索(java api)

package com.qlyd.searchhelper;

import java.util.Map;

import net.sf.json.JSONObject;

import org.elasticsearch.action.search.SearchRequestBuilder;

import org.elasticsearch.action.search.SearchResponse;

import org.elasticsearch.action.search.SearchType;

import org.elasticsearch.client.Client;

import org.elasticsearch.common.text.Text;

import org.elasticsearch.index.query.QueryBuilders;

import org.elasticsearch.search.SearchHit;

import org.elasticsearch.search.SearchHits;

import org.elasticsearch.search.highlight.HighlightField;

import com.qlyd.business.newsinfo.po.NewsInfo;

import com.qlyd.common.QlydConstants;

import com.qlyd.utils.ESTools;

import com.qlyd.utils.JsonUtils;

/**

*

*

* @类编号:

* @类名称:ElasticSearchHandler

* @内容摘要: //搜索控制类

* @author:鹿伟伟

* @创建日期:2016年3月22日 下午3:26:52

* @修改人:

* @修改日期:

* @修改描述:简单描述修改的内容

* @version 1.0.0

*

*/

public class ElasticSearchHandler {

private Client client = ESTools.getClient();

public void searcher(String key, String indexId, String type) {
try { // 创建查询索引,参数productindex表示要查询的索引库为productindex
SearchRequestBuilder searchRequestBuilder = client
.prepareSearch(indexId); // 设置查询索引类型,setTypes("productType1", "productType2","productType3");
// 用来设定在多个类型中搜索
searchRequestBuilder.setTypes(type);
// 设置查询类型 1.SearchType.DFS_QUERY_THEN_FETCH = 精确查询 2.SearchType.SCAN
// = 扫描查询,无序
searchRequestBuilder.setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
// 设置查询关键词
searchRequestBuilder
.setQuery(QueryBuilders.termQuery("title", key)); // // 查询过滤器过滤价格在4000-5000内
// 这里范围为[4000,5000]区间闭包含,搜索结果包含价格为4000和价格为5000的数据
// searchRequestBuilder.setFilter(FilterBuilders.rangeFilter("price")
// .from(4000).to(5000));
//
// // 分页应用
// searchRequestBuilder.setFrom(0).setSize(3); // 设置是否按查询匹配度排序
searchRequestBuilder.setExplain(true); // 设置高亮显示
searchRequestBuilder.addHighlightedField("title");
searchRequestBuilder
.setHighlighterPreTags("<span style=\"color:red\">");
searchRequestBuilder.setHighlighterPostTags("</span>");
// 执行搜索,返回搜索响应信息
SearchResponse response = searchRequestBuilder.execute()
.actionGet();

// System.out.println(response.toString());

// 获取搜索的文档结果

SearchHits searchHits = response.getHits();

SearchHit[] hits = searchHits.getHits();

// ObjectMapper mapper = new ObjectMapper();

for (int i = 0; i < hits.length; i++) {

SearchHit hit = hits[i];

// 将文档中的每一个对象转换json串值

String json = hit.getSourceAsString();

// 将json串值转换成对应的实体对象

// Product product = mapper.readValue(json, Product.class);

NewsInfo newsInfo = JsonUtils

.readToObject(json, NewsInfo.class);

// 获取对应的高亮域

Map