1.为工具类添加方法
package com.zhangdi.springboot.elasticsearch;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.client.IndicesAdminClient;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
public class ESClientUtil {
private static volatile TransportClient client;
public static final String CLUSTER_NAME="elasticsearch";
public static final String HOST_IP="192.168.1.12";
public static final int TCP_PORT=9300;
static Settings settings = Settings.builder().put("cluster.name",CLUSTER_NAME).build();
public static TransportClient getClient() {
try {
client = new PreBuiltTransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(HOST_IP), TCP_PORT));
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return client;
}
//先对client加锁
//获取TransportClient对象
public static TransportClient getSingleClient() {
if (client==null) {
synchronized (TransportClient.class) {
}
if (client==null) {
try {
client = new PreBuiltTransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(HOST_IP), TCP_PORT));
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return client;
}
//获取索引管理对象
public static IndicesAdminClient getIndicesAdminClient() {
return getSingleClient().admin().indices();
}
//创建索引
public static boolean createIndex(String indexName,int shards, int replicas) {
Settings settings = Settings.builder()
.put("index.number_of_shards",shards).build();
// mapping
CreateIndexResponse response = getIndicesAdminClient()
.prepareCreate(indexName.toLowerCase())
.setSettings(settings)// setting
.execute().actionGet();
return response.isAcknowledged();
}
//删除索引
public static boolean deleteIndex(String indexName) {
// mapping
DeleteIndexResponse response = getIndicesAdminClient()
.prepareDelete(indexName.toLowerCase())
.execute().actionGet();
return response.isAcknowledged();
}
//设置mapping
public static boolean setMapping(String indexName,String type,String mapping) {
getIndicesAdminClient()
.preparePutMapping(indexName)
.setType(type)
.setSource(mapping,XContentType.JSON)
.get();
return false;
}
}
2.索引和文档的CRUD
package com.zhangdi.springboot;
import java.io.IOException;
import java.math.BigDecimal;
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.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.json.JSONObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringRunner;
import org.thymeleaf.util.EscapedAttributeUtils;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import com.zhangdi.springboot.elasticsearch.ESClientUtil;
import com.zhangdi.springboot.service.UserService;
import com.zhangdi.springboot.statistics.MarketDataManager;
import com.zhangdi.springboot.statistics.Statistics;
import com.zhangdi.springboot.statistics.StatisticsData;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootApplicationTests {
@Autowired
UserService userService;
@Test
@Rollback(false)
public void contextLoads() {
}
//测试连接es
@Test
public void testSingleES() {
System.setProperty("es.set.netty.runtime.available.processors", "false");
TransportClient client = ESClientUtil.getSingleClient();
TransportClient client1 = ESClientUtil.getSingleClient();
TransportClient client2 = ESClientUtil.getSingleClient();
System.out.println(client);
System.out.println(client1);
System.out.println(client2);
}
//测试创建索引
@Test
public void testCreateIndex() {
System.setProperty("es.set.netty.runtime.available.processors", "false");
boolean bool = ESClientUtil.createIndex("aaaa", 5, 1);
System.out.println(bool);
}
//测试删除索引
@Test
public void testDeleteIndex() {
System.setProperty("es.set.netty.runtime.available.processors", "false");
boolean bool = ESClientUtil.deleteIndex("aaaa");
System.out.println(bool);
}
//测试设置mapping
@Test
public void testSetMapping() {
System.setProperty("es.set.netty.runtime.available.processors", "false");
try {
XContentBuilder builder=XContentFactory.jsonBuilder()
.startObject()
.startObject("properties")
.startObject("user")
.field("type", "text")
.endObject()
.startObject("postdate")
.field("type", "date")
.endObject()
.startObject("message")
.field("type", "text")
.endObject()
.endObject()
.endObject();
System.out.println(builder.toString());
ESClientUtil.setMapping("aaaa", "bbbb", builder.string());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//测试添加文档
@Test
public void putDocument1() {
System.setProperty("es.set.netty.runtime.available.processors", "false");
String json = "{" +"\"user\":\"kimchy\","+
"\"postdate\":\"2013-01-30\","+
"\"message\":\"learn Elasticsearch\""+"}";
TransportClient client = ESClientUtil.getSingleClient();
IndexResponse response = client.prepareIndex("aaaa", "bbbb", "1")
.setSource(json,XContentType.JSON)
.get();
RestStatus restStatus = response.status();
System.out.println(restStatus.getStatus());
}
//测试添加文档
@Test
public void putDocument2() {
System.setProperty("es.set.netty.runtime.available.processors", "false");
Map<String, String> map = new HashMap<String, String>();
map.put("user", "toney");
map.put("postdate", "2018-01-12");
map.put("message", "learn java");
TransportClient client = ESClientUtil.getSingleClient();
IndexResponse response = client.prepareIndex("aaaa", "bbbb", "2")
.setSource(map,XContentType.JSON)
.get();
RestStatus restStatus = response.status();
System.out.println(restStatus.getStatus());
}
//测试添加文档
@Test
public void putDocument3() {
System.setProperty("es.set.netty.runtime.available.processors", "false");
XContentBuilder builder;
try {
builder = XContentFactory.jsonBuilder()
.startObject()
.field("user", "tom")
.field("postdate", "2019-01-02")
.field("message", "learn python")
.endObject();
String json = builder.string();
TransportClient client = ESClientUtil.getSingleClient();
IndexResponse response = client.prepareIndex("aaaa", "bbbb", "3")
.setSource(json,XContentType.JSON)
.get();
RestStatus restStatus = response.status();
System.out.println(restStatus.getStatus());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//测试获取文档
@Test
public void testES() {
System.setProperty("es.set.netty.runtime.available.processors", "false");
TransportClient client = ESClientUtil.getSingleClient();
if(client!=null) {
GetResponse getResponse = client.prepareGet("blog", "article", "1").execute().actionGet();
System.out.println(getResponse.getSourceAsString());
System.out.println(getResponse.getSourceAsMap());
}
}
//测试更新文档
@Test
public void testUpdateDocument() {
System.setProperty("es.set.netty.runtime.available.processors", "false");
TransportClient client = ESClientUtil.getSingleClient();
Map<String, String> map = new HashMap<String, String>();
map.put("user", "jim");
map.put("postdate", "2018-01-12");
map.put("message", "learn javascript");
UpdateResponse response = client.prepareUpdate("aaaa", "bbbb", "3").setDoc(map).get();
RestStatus restStatus = response.status();
System.out.println(restStatus);
}
//测试删除文档
@Test
public void testDeleteDocument() {
System.setProperty("es.set.netty.runtime.available.processors", "false");
TransportClient client = ESClientUtil.getSingleClient();
DeleteResponse response = client.prepareDelete("aaaa", "bbbb", "3").execute().actionGet();
RestStatus restStatus = response.status();
System.out.println(restStatus);
}
//测试搜索文档
@Test
public void testSearchDocument() {
System.setProperty("es.set.netty.runtime.available.processors", "false");
TransportClient client = ESClientUtil.getSingleClient();
TermQueryBuilder termQuery = QueryBuilders.termQuery("user", "toney");
SearchResponse response = client.prepareSearch("aaaa")
.setQuery(termQuery)
.setTypes("bbbb")
.execute()
.actionGet();
SearchHits hits = response.getHits();
for(SearchHit hit:hits) {
System.out.println(hit.getSourceAsString());
System.out.println(hit.getScore());
}
}
//设置分词的mapping
@Test
public void testMappingIK() {
System.setProperty("es.set.netty.runtime.available.processors", "false");
XContentBuilder builder;
try {
builder = XContentFactory.jsonBuilder()
.startObject()
.startObject("properties")
.startObject("id")
.field("type", "long")
.endObject()
.startObject("title")
.field("type", "text")
.field("analyzer","ik_max_word")
.field("search_analyzer","ik_max_word") //指定搜索分词器 get mapping查看不到
.field("boost", 2) //增加评分
.endObject()
.startObject("content")
.field("type", "text") //keyword 不会建立索引
.field("analyzer", "ik_max_word")
.field("search_analyzer", "ik_max_word")
.endObject()
.startObject("postdate")
.field("type", "date")
.field("format", "yyyy-MM-dd HH:mm:ss")
.endObject()
.endObject()
.endObject();
System.out.println(builder.toString());
ESClientUtil.setMapping("cccc", "dddd", builder.string());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}