欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ElasticSearch

程序员文章站 2022-07-01 09:54:38
...
ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch

java简单示例:


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.update.UpdateRequestBuilder;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.Requests;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;


/*********************************************************************************
//*
//* Filename: ESClient.java
//* Revision: 1.0
//* Author: <makun>
//* Created On: 2015年10月29日
//* Modified by:
//* Modified On:
//*
//* Description: <description>
/********************************************************************************/

public class ESClient {

private Client client;

public void init() {
// client = new TransportClient().addTransportAddress(new InetSocketTransportAddress("ip", 9300));
//172.30.150.102----------9300
//172.30.150.101----------9300
client = elasticsearchClient();
}

public Client elasticsearchClient() {
TransportClient esClient = new TransportClient(buildNodeSettings());
esClient.addTransportAddress(new InetSocketTransportAddress("ip", 9300));
return esClient;
}

public void close() {
client.close();
}

private Settings buildNodeSettings() {
Map<String, String> settings = new HashMap<String, String>();
settings.put("cluster.name", "elasticsearch");
ImmutableSettings.Builder builder = ImmutableSettings.settingsBuilder().put(settings);
return builder.build();
}

/**
* 创建索引
*/
public void createIndex() {
List<String> jsondata = DataFactory.getInitJsonData();
for (int i = 0 ; i < jsondata.size() ; i++) {
client.prepareIndex("mk_data", "t_account", String.valueOf(i)).setSource(jsondata.get(i)).execute().actionGet();
}
System.out.println("createIndex successful.");
}

/**
* 删除索引
*/
public void deleteIndex() {
// DeleteResponse response = client.prepareDelete("mk_data", "t_account", "0") .setOperationThreaded(false).execute().actionGet();
client.prepareDelete("mk_data", "t_account", "0").setOperationThreaded(false).execute().actionGet();
System.out.println("deleteIndex successful.");
}

/**
* 修改
* @param model
* @param indexName
* @param typeName
* @param id
*/
public void update(Medicine model, String indexName, String typeName, String id) {
IndexRequest indexRequest = new IndexRequest();
indexRequest.source(JsonHelper.toJsonString(model));
UpdateRequestBuilder updateRequestBuilder = client.prepareUpdate(indexName, typeName, id);
updateRequestBuilder.setDoc(indexRequest).execute().actionGet();;
System.out.println("updateIndex successful.");
}

/**
* 修改,如果不存在,新增
* @param model
* @param indexName
* @param typeName
* @param id
*/
public void upsert(Medicine model, String indexName, String typeName, String id) {
IndexRequest indexRequest = new IndexRequest();
indexRequest.source(JsonHelper.toJsonString(model));
UpdateRequestBuilder updateRequestBuilder = client.prepareUpdate(indexName, typeName, id);
updateRequestBuilder.setDocAsUpsert(true).setUpsert(indexRequest).setDoc(indexRequest).execute().actionGet();;
System.out.println("upsertIndex successful.");
}

public void refresh(String indexName) {
client.admin().indices().refresh(Requests.refreshRequest(indexName)).actionGet();
}
/**
* 执行搜索
* @param queryBuilder
* @param indexname
* @param type
* @return
*/
public List<Medicine> searcher(QueryBuilder queryBuilder, String indexname, String type) {
List<Medicine> list = new ArrayList<Medicine>();
SearchResponse searchResponse = client.prepareSearch(indexname).setTypes(type).setQuery(queryBuilder).execute().actionGet();
SearchHits hits = searchResponse.getHits();
System.out.println("查询到记录数=" + hits.getTotalHits());
SearchHit[] searchHists = hits.getHits();
if (searchHists.length > 0) {
for (SearchHit hit : searchHists) {
Integer id = (Integer) hit.getSource().get("id");
String name = (String) hit.getSource().get("name");
String function = (String) hit.getSource().get("funciton");
list.add(new Medicine(id, name, function));
}
}
return list;
}

/**
* 查询
*/
public void search() {
SearchRequestBuilder builder = client.prepareSearch("mk_data").setTypes("t_account").setSearchType(SearchType.DEFAULT).setFrom(0).setSize(100);
BoolQueryBuilder qb = QueryBuilders.boolQuery().must(new QueryStringQueryBuilder("止咳糖浆").field("name")).should(new QueryStringQueryBuilder("止咳糖浆").field("function"));
builder.setQuery(qb);
SearchResponse response = builder.execute().actionGet();
System.out.println(" " + response);
}

public static void main(String[] args) {
ESClient client = new ESClient();
String indexName = "mk_data";
String typeName = "t_account";
client.init();
// QueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery("name", "感冒");
// List<Medicine> result = client.searcher(queryBuilder, indexName, typeName);
// System.out.println(result.size());
// client.createIndex();
// client.search();
// client.deleteIndex();
Medicine model = new Medicine();
model.setId(1);
model.setName("发烧 发烧 发烧");
model.setFunction("万通筋骨灵");
client.update(model, indexName, typeName, model.getId().toString());
client.refresh(indexName);
client.close();
}
}


[b]JSONUTILS[/b]

import com.fasterxml.jackson.databind.ObjectMapper;
/*********************************************************************************
//*
//* Filename: JsonUtils.java
//* Revision: 1.0
//* Author: makun
//* Created On: 2015年10月30日
//* Modified by:
//* Modified On:
//*
//* Description: <description>
/********************************************************************************/

public class JsonUtils {

public static <T> T fromJsonString(String str, Class<?> clazz) {
ObjectMapper objectMapper = new ObjectMapper();
try {
return (T) objectMapper.readValue(str, clazz);
}
catch (Exception e) {
LogUtils.error(e, "JsonUtils fromJsonString error");
return null;
}
}

public static String toJsonString(Object object) {
ObjectMapper objectMapper = new ObjectMapper();
try {
return objectMapper.writeValueAsString(object);
}
catch (Exception e) {
LogUtils.error(e, "JsonUtils toJsonString error");
return "";
}
}

}