前提:请将es的环境(es服务,IK中文分词器,head-master插件等)搭建好,本文章使用的是java代码实现的es的增删改查操作(使用的是测试环境)
在pom文件中导入坐标(第一次导入时间可能有点长,请耐心等待)
org.elasticsearch.client
transport
5.6.8
junit
junit
4.12
com.alibaba
fastjson
1.2.56
代码中使用了实体类,请自行创建实体类即可,提供get/set方法和toString方法
package com.itcode.test2;
import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.Requests;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
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.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
public class InitEsData {
public static TransportClient transportClient;
@Before
public void init() throws Exception {
//创建访问客户端对象
transportClient = new PreBuiltTransportClient(Settings.EMPTY)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
}
@After
public void destory() {
transportClient.close();
}
//创建没有映射关系的索引
@Test
public void createIndex() throws IOException {
transportClient.admin().indices().prepareCreate("blog2").get();
}
//删除索引
@Test
public void daleteIndex() {
transportClient.admin().indices().prepareDelete("blog2").get();
}
//创建有映射关系的索引
@Test
public void testCreateSearchIndex() throws ExecutionException, InterruptedException, IOException {
IndicesExistsResponse blog2 = transportClient.admin().indices().prepareExists("blog2").get();
if (!blog2.isExists()) {
CreateIndexResponse response = transportClient.admin().indices().prepareCreate("blog2").get();
}
//添加映射
/**
*
* 格式:
* "mappings" :
* 从这里开始
* {
* "article" : {
* "properties" : {
* "id" : { "type" : "long", "store":"yes" },
* "content" : { "type" : "string" , "store":"yes" , "analyzer":"ik_smart"},
* "title" : { "type" : "string", "store":"yes" , "analyzer":"ik_smart" }
* }
* }
* }
*/
//方式一创建:
/*
Map id = new HashMap();
id.put("type", "long");
id.put("store", "yes");
Map content = new HashMap();
content.put("type","string");
content.put("store","yes");
content.put("analyzer","ik_smart");
Map title = new HashMap();
title.put("type","string");
title.put("store","yes");
title.put("analyzer","ik_smart");
Map properties = new HashMap();
properties.put("id",id);
properties.put("content",content);
properties.put("title",title);
Map articles = new HashMap();
articles.put("properties",properties);
Map mapping = new HashMap();
mapping.put("articles",articles);
PutMappingRequest request = Requests.putMappingRequest("blog2").type("articles").source(mapping);
*/
//方式二 通过XContentFactory创建json对象来实现(比较麻烦)
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject()
.startObject("article")
.startObject("properties")
.startObject("id")
.field("type", "long")
.field("store", "yes")
.endObject()
.startObject("title")
.field("type", "string")
.field("store", "yes")
.field("analyzer", "ik_smart")
.endObject()
.startObject("content")
.field("type", "string")
.field("store", "yes")
.field("analyzer", "ik_smart")
.endObject()
.endObject()
.endObject()
.endObject();
PutMappingRequest request = Requests.putMappingRequest("blog2").type("article").source(builder);
PutMappingResponse putMappingResponse = transportClient.admin().indices().putMapping(request).get();
System.out.println(putMappingResponse.isAcknowledged());
}
//创建文档
@Test
public void createDocument() throws IOException {
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject()
.field("id", 1L)
.field("title", "ElasticSearch是一个基于Lucene的搜索服务器")
.field("content", "它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是 用Java开发的,并作为Apache许可条款下的开放源码发布,是当前流行的企业级搜索引擎。设计用于云计算中,能 够达到实时搜索,稳定,可靠,快速,安装使用方便。")
.endObject();
transportClient.prepareIndex("blog2", "article", "1").setSource(builder).get();
}
//通过对象创建document
@Test
public void createDocumentByObject() {
Article article = new Article();
article.setId(2L);
article.setTitle("搜索功能其实也挺简单的");
article.setContent("我们希望我们的搜索解决方案要快,我们希望有一个零配置和一个完全免费的搜索模式,我们希望能够简单地使用JSON通过HTTP的索引数据,我们希望我们的搜索服务器始终可用,我们希望能够一台开始并扩展到数百,我们要实时搜索,我们要简单的多租户,我们希望建立一个云的解决方案。Elasticsearch旨在解决所有这些问题和更多的问题。");
String jsonString = JSON.toJSONString(article);
transportClient.prepareIndex("blog2", "article", article.getId() + "")
.setSource(jsonString, XContentType.JSON).get();
}
//修改文档
/**
* 关于修改文档,可以通过prepareIndex.直接将id相同的对象上传覆盖就达到了修改的目的
* 也可以通过prepareUpdate上传修改,或者直接调用update也可以
*/
@Test
public void updateDocumentByObject() throws ExecutionException, InterruptedException {
Article article = new Article();
article.setId(2L);
article.setTitle("搜索功能其实也挺简单的");
article.setContent("ok,我们希望我们的搜索解决方案要快,我们希望有一个零配置和一个完全免费的搜索模式,我们希望能够简单地使用JSON通过HTTP的索引数据,我们希望我们的搜索服务器始终可用,我们希望能够一台开始并扩展到数百,我们要实时搜索,我们要简单的多租户,我们希望建立一个云的解决方案。Elasticsearch旨在解决所有这些问题和更多的问题。");
String jsonString = JSON.toJSONString(article);
UpdateResponse response = transportClient.prepareUpdate("blog2", "article", article.getId() + "").setDoc(jsonString, XContentType.JSON).get();
// UpdateResponse response = transportClient.update(new UpdateRequest("blog2", "article", article.getId()+"").doc(jsonString, XContentType.JSON)).get();
System.out.println(response.status());
}
//删除文档
@Test
public void deleteDocument() throws ExecutionException, InterruptedException {
//DeleteResponse response = transportClient.prepareDelete("blog2", "article", "2").get();
DeleteResponse response = transportClient.delete(new DeleteRequest("blog2", "article", "2")).get();
System.out.println(response.status());
}
//插入批量数据
@Test
public void addData(){
for (int i = 0; i < 100; i++) {
Article article = new Article();
article.setId((long)i);
article.setTitle(i + "好的修改搜索工作其实很快乐");
article.setContent(i+"我们希望我们的搜索解决方案要快,我们希望有一个零配置和一个完全免费的搜索模式,我们希望能够简单地使用JSON通过HTTP的索引数据,我们希望我们的搜索服务器始终可用,我们希望能够一台开始并扩展到数百,我们要实时搜索,我们要简单的多租户,我们希望建立一个云的解决方案。Elasticsearch旨在解决所有这些问题和更多的问题。");
IndexResponse response = transportClient.prepareIndex("blog2", "article", article.getId() + "").setSource(JSON.toJSONString(article), XContentType.JSON).get();
}
}
//分页查询和排序
@Test
public void searchPage() {
SearchRequestBuilder builder = transportClient.prepareSearch("blog2").setTypes("article").setQuery(QueryBuilders.matchAllQuery());
//分页公式(pageNum-1)*pageSize
//from从第几条开始记录,size记录几条
builder.setFrom(0).setSize(10);
//参与排序的字段不能是字符串类型的数据
builder.addSort("id", SortOrder.DESC);
SearchResponse response = builder.get();
//获取结果
SearchHits hits = response.getHits();
//查出结果数
System.out.println(hits.getTotalHits());
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
System.out.println(hit.getSource().get("title"));
}
}
//查询结果高亮显示
@Test
public void hightlightQuery(){
//这里的高亮查询使用的是term词条查询,指定高亮的属性
SearchRequestBuilder builder = transportClient.prepareSearch("blog2").setTypes("article")
.setQuery(QueryBuilders.termQuery("content","搜索"));
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.preTags("");
highlightBuilder.postTags("");
highlightBuilder.field("content");
builder.highlighter(highlightBuilder);
SearchResponse response = builder.get();
SearchHits hits = response.getHits();
System.out.println("共查到"+hits.getTotalHits());
for (SearchHit hit : hits) {
Text[] contents = hit.getHighlightFields().get("content").getFragments();
for (Text content : contents) {
System.out.println(content);
}
}
}
}