前面写了搭建,今天写一篇关于Java api的增删改查以及全字段查询和高亮展示,官方api 地址[https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/index.html]。
一、增
首先添加相应的pom依赖、resource 文件
resource文件 log4j.properties
###Console ###
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern = %d %p[%C:%L]- %m%n
获取一个TransportClient的实例去连接es类似连接数据库代码
Settings settings=Settings.builder().put("cluster.name","yourclustername").build();
TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("yourhostaddress"), 9300));
Map testMap = new HashMap<>();
testMap.put("title","java 编程思想");
testMap.put("id",1);
//单个Map插入
IndexResponse response = client.prepareIndex("索引","yourtype",testMap.get("id")+"").setSource(testMap).get();
System.out.println(response.getResult());
client.close();
//批量插入
List
二、删除
//删除id为0的ES里的数据
DeleteResponse response = client.prepareDelete("索引","yourtype","0").get();
System.out.print(response.getResult());
三、修改(就是添加ID是里面已有的ID覆盖以前的数据)
//修改ES里id为1的那条数据title改为Tinking in Java
testMap.put("title","Thinking in Java");
IndexResponse response = client.prepareIndex("索引","yourtype","1").setSource(testMap).get();
System.out.println(response.getResult());
client.close();
四、查
QueryBuilder qb = QueryBuilders.multiMatchQuery("yourSearchString","_all");
HighlightBuilder highlightBuilder=new HighlightBuilder().field("*").requireFieldMatch(false);
highlightBuilder.preTags("");
highlightBuilder.postTags("");
String[] yourTypes={yourTypes};
if (yourTypes==""||yourTypes==null){
yourTypes=new String[0];
}
SearchResponse response=client.prepareSearch("索引").setTypes(yourTypes).setFrom(pageIndex).setSize(pageSize).setQuery(qb).highlighter(highlightBuilder).execute().actionGet();
SearchHits searchHits=response.getHits();
List
索引和type是要你自己去手动填写的,这是我看了官方api写的一个列子 不足之处希望大家多多指教!
今天就写这么多了,大家可以留言互相讨论~晚安~