spring boot 整合 elasticsearch 创建索引库 映射

spring boot 整合 elasticsearch

1 导入依赖

<dependencies>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>6.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>6.2.1</version>
        </dependency>
    </dependencies>

2 配置文件

server:
  port: ${port:40100}
spring:
  application:
    name: search
search:
  elasticsearch:
    hostlist: ${eshostlist:127.0.0.1:9200} #多个结点中间用逗号分隔

3 创建连接客户端

@Configuration
public class ElasticsearchConfig {

    @Value("${search.elasticsearch.hostlist}")
    private String hostlist;

    @Bean
    public RestHighLevelClient restHighLevelClient(){
        //解析hostlist配置信息
        String[] split = hostlist.split(",");
        //创建HttpHost数组,其中存放es主机和端口的配置信息
        HttpHost[] httpHostArray = new HttpHost[split.length];
        for(int i=0;i<split.length;i++){
            String item = split[i];
            httpHostArray[i] = new HttpHost(item.split(":")[0], Integer.parseInt(item.split(":")[1]), "http");
        }
        //创建RestHighLevelClient客户端
        return new RestHighLevelClient(RestClient.builder(httpHostArray));
    }

    //项目主要使用RestHighLevelClient,对于低级的客户端暂时不用
    @Bean
    public RestClient restClient(){
        //解析hostlist配置信息
        String[] split = hostlist.split(",");
        //创建HttpHost数组,其中存放es主机和端口的配置信息
        HttpHost[] httpHostArray = new HttpHost[split.length];
        for(int i=0;i<split.length;i++){
            String item = split[i];
            httpHostArray[i] = new HttpHost(item.split(":")[0], Integer.parseInt(item.split(":")[1]), "http");
        }
        return RestClient.builder(httpHostArray).build();
    }

}

创建索引库 映射

注 : es 中索引库相当于数据库中的表 映射相当于数据库中的字段
http方式创建索引库

put http://localhost:9200/索引库名称
{
    "settings":{
    "index":{
        "number_of_shards":1,  分片数量
        "number_of_replicas":0  副本数量
        }
    }
}

http方式创建映射

post:http://localhost:9200/索引库名称/类型名称/_mapping

{
    "properties":{
        "description":{
            "type":"text", 数据类型
            "analyzer":"ik_max_word", 创建索引时细粒度分词
            "search_analyzer":"ik_smart" 搜索时粗粒度分词
        },
        "name":{
            "type":"text",
            "analyzer":"ik_max_word",
            "search_analyzer":"ik_smart"
        },
        "pic":{
            "type":"text",
            "index":false  不创建索引,搜不到
        },
        "price":{
            "type":"float" 数值类型
        },
        "studymodel":{
            "type":"keyword"  精确匹配
        },
        "timestamp":{
            "type":"date",  日期类型
            "format":"yyyy‐MM‐dd HH:mm:ss||yyyy‐MM‐dd||epoch_millis"
        }
    }

http方式插入文档

put http://localhost:9200/索引库名称/类型名称

{
    "name":"spring开发基础",
    "description":"spring 在java领域非常流行,java程序员都在用。",
    "studymodel":"201001",
    "price":88.6,
    "timestamp":"2018‐02‐24 19:11:35",
    "pic":"group1/M00/00/00/wKhlQFs6RCeAY0pHAAJx5ZjNDEM428.jpg"
}

java api 方式创建 索引库并

package com.search;


import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.IndicesClient;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
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.context.junit4.SpringRunner;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@SpringBootTest(classes = SearchApplication.class)
@RunWith(SpringRunner.class)
public class Test1 {

    @Autowired
    RestHighLevelClient client;

    @Autowired
    RestClient restClient;

    //创建索引库
    @Test
    public void test01() throws IOException {
        //创建索引请求对象,并设置索引名称
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("es_article");
        //设置索引参数 分片数1 副本数0 
        createIndexRequest.settings(Settings.builder().put("number_of_shards",1).
                put("number_of_replicas",0));
        //设置映射
        createIndexRequest.mapping("doc","{\n" +
                "    \"properties\":{\n" +
                "        \"name\":{\n" +
                "            \"type\":\"text\"\n" +
                "        },\n" +
                "        \"description\":{\n" +
                "            \"type\":\"text\",\n" +
                "            \"analyzer\":\"ik_max_word\",\n" +
                "            \"search_analyzer\":\"ik_smart\"\n" +
                "        },\n" +
                "        \"studymodel\":{\n" +
                "            \"type\":\"keyword\"\n" +
                "        },\n" +
                "        \"timestamp\":{\n" +
                "            \"type\":\"date\",\n" +
                "            \"format\":\"yyyy‐MM‐dd HH:mm:ss||yyyy‐MM‐dd\"\n" +
                "        }\n" +
                "    }\n" +
                "}", XContentType.JSON);
                        //创建索引操作客户端
                        IndicesClient indices = client.indices();
        //创建响应对象
        CreateIndexResponse createIndexResponse = indices.create(createIndexRequest);
        //得到响应结果
        boolean acknowledged = createIndexResponse.isAcknowledged();
        System.out.println(acknowledged);
    }
    
    //添加文档
    @Test
    public void test02() throws IOException {
        //准备json数据
        Map<String, Object> jsonMap = new HashMap<>(); 
        jsonMap.put("name", "Bootstrap开发");
        jsonMap.put("description", "Bootstrap是由Twitter推出的一个前台页面开发框架,是一个非常流行的开发框架,此框架集成了多种页面效果。此开发框架包含了大量的CSS、JS程序代码,可以帮助开发者(尤其是不擅长页面开发的程序人员)轻松    的实现一个不受浏览器限制的精美界面效果");
        jsonMap.put("studymodel", "201001");
        jsonMap.put("id","1");
        SimpleDateFormat dateFormat =new SimpleDateFormat("yyyy‐MM‐dd HH:mm:ss"); 
        jsonMap.put("timestamp", dateFormat.format(new Date())); 
        //索引请求对象
        IndexRequest indexRequest = new IndexRequest("es_article","doc");
        //指定索引文档内容
        indexRequest.source(jsonMap);
        //索引响应对象
        IndexResponse indexResponse = client.index(indexRequest);
        DocWriteResponse.Result result = indexResponse.getResult();
        System.out.println(result);
    }
    
    //删除文档
    @Test
    public void test03() throws IOException {
        //删除文档id
        String id = "CFpcGnQB4Zx9zTygBfYS";
        //删除索引请求对象
        DeleteRequest deleteRequest = new DeleteRequest("es_article","doc",id);
        //响应对象
        DeleteResponse deleteResponse = client.delete(deleteRequest);
        //获取响应结果
        DocWriteResponse.Result result = deleteResponse.getResult(); 
        System.out.println(result);
    }

}

  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值