1、首先使用本地Windows安装的ES进行环境测试
第一步:创建索引
使用postman 发送PUT请求:http://localhost:9200/索引名称
{
"settings": {
"index": {
"number_of_shards": 1,
"number_of_replicas": 0
}
}
}
第二步:创建映射
使用postman 发送POST请求:http://localhost:9200/索引名称/类型名称/_mapping
{
"properties": {
"name": {
"type": "text"
},
"description": {
"type": "text"
},
"studymodel": {
"type": "keyword"
}
}
}
第三步: 创建文档
使用postman 发送PUT或者POS请求 http://localhost:9200/索引名称/类型名称/id值 (如果不指定id值ES会自动生成ID)
{
"name": "Bootstrap开发框架",
"description": "Bootstrap是由Twitter推出的一个前台页面开发框架,在行业之中使用较为广泛。",
"studymodel": "2020"
}
第四步: 搜索文档
1、根据课程id查询文档
使用postman 发送GET请求 http://localhost:9200/索引名称/类型名称/id值
至此环境测试OK了、其他检索方式不进行演示…
2、Java、maven环境、连接Elasticsearch简单CRUD操作
pom.xml中导入ES客户端依赖
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>6.2.4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
效果展示
3、最终测试代码
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Test;
/***
* ES 根据ID检索文档测试
* @author yandongfa
* @Date 2020年4月17日 下午6:59:13
* @version V1.0
*/
public class EsDemo {
@Test
public void test() throws UnknownHostException{
//1、指定ES集群名称、cluster.name:固定写法(配置集群名称)、ydf_course:集群名称(默认是elasticsearch)
Settings settings = Settings.builder().put("cluster.name", "ydf_course").build();
//2、创建访问ES服务器的客户端、127.0.0.1:本机IP地址、 9300 :集群结点之间通信端口
TransportClient client = new PreBuiltTransportClient(settings)
.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
//3、数据查询、book:索引名称、doc:类型名称、1:根据id=1查询
GetResponse response = client.prepareGet("book", "doc", "1").execute().actionGet();
//4、得到查询出的数据、返回JSON字符串
System.out.println(response.getSourceAsString());
//5、关闭客户端
client.close();
}
}