Elastic search入门到集群实战操作详解(原生API操作、spring( 二 )

runtimetrueorg.springframework.bootspring-boot-configuration-processortrueorg.projectlomboklomboktrueorg.springframework.bootspring-boot-starter-testtestorg.springframework.bootspring-boot-starter-loggingcom.google.code.gsongson2.8.5org.apache.commonscommons-lang33.8.1commons-beanutilscommons-beanutils1.9.1org.elasticsearch.clientelasticsearch-rest-high-level-client6.4.3org.elasticsearch.clientelasticsearch-rest-client6.4.3org.elasticsearchelasticsearch6.4.3org.springframework.bootspring-boot-maven-pluginorg.projectlomboklombok
2.2.3.配置文件
我们在下创建.yml
2.3.索引库及映射
创建索引库的同时,我们也会创建type及其映射关系,但是这些操作不建议使用java客户端完成,原因 如下:
因此,这些操作建议还是使用我们昨天学习的Rest风格API去实现 。
我们接下来以这样一个商品数据为例来创建索引库:

Elastic search入门到集群实战操作详解(原生API操作、spring

文章插图
public class Product {private Long id;private String title; //标题private String category;// 分类private String brand; // 品牌private Double price; // 价格private String images; // 图片地址}
分析一下数据结构:
我们可以编写这样的映射配置:
PUT /lgt{"settings": {"number_of_shards": 3,"number_of_replicas": 1},"mappings": {"item": {"properties": {"id": {"type": "keyword"},"title": {"type": "text","analyzer": "ik_max_word"},"category": {"type": "keyword"},"brand": {"type": "keyword"},"images": {"type": "keyword","index": false},"price": {"type": "double"}}}}}
2.4.索引数据操作
有了索引库,我们接下来看看如何新增索引数据
操作MYSQL数据库:
1.获取数据库连接
2.完成数据的增删改查
3.释放资源
2.4.1.初始化客户端
完成任何操作都需要通过客户端,看下如何创建 。
private static RestHighLevelClient restHighLevelClient;private Gson gson = new Gson();/*** 初始化客户端*/@BeforeAllstatic void init() {System.out.println("执行了");RestClientBuilder clientBuilder = RestClient.builder(new HttpHost("127.0.0.1", 9201, "http"),new HttpHost("127.0.0.1", 9202, "http"),new HttpHost("127.0.0.1", 9203, "http"));restHighLevelClient = new RestHighLevelClient(clientBuilder);}/*** 关闭客户端*/@AfterAllstatic void close() throws IOException {restHighLevelClient.close();}
2.4.2.新增文档
/*** 新增文档* @throws IOException*/@Testvoid addDoc() throws IOException {//1.创建文档Product product = new Product();product.setBrand("华为");product.setCategory("手机");product.setId(1L);product.setImages("http://image.huawei.com/1.jpg");product.setTitle("华为P50就是棒");product.setPrice(88.88d);//2.将文档数据转换为json格式String source = gson.toJson(product);//3.创建索引请求对象//public IndexRequest(String index, String type, String id)IndexRequest request = new IndexRequest("lagou","item",product.getId().toString());//4.发出请求request.source(source, XContentType.JSON);IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);System.out.println(response);}