springboot2.1.8+elasticsearch7.3.2(二),pom.xml文件和ik中文分词插件的使用以及创建索引代码

我的DEMO项目下载:https://gitee.com/zhuhongliang/soringboot_elastic_search_732.git

下载elasticsearch-analysis-ik-7.3.2.zip :https://github.com/medcl/elasticsearch-analysis-ik/releases
在\elasticsearch-7.3.2\plugins 目录里创建文件夹ik,然后把zip全部解压进去
用命令查看当前的插件:

PS C:\data\elasticsearch-7.3.2\bin> .\elasticsearch-plugin.bat list
ik

然后重启elasticsearch
在一大堆启动输出内容里能发现

[2019-09-20T23:52:09,550][INFO ][o.e.p.PluginsService     ] [node-1] loaded plugin [analysis-ik]

表示ik安装成功。

项目文件:

pom.xml在依赖elasticsearch-rest-high-level-client的时候,需要把一些内部低版本的依赖去除

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.zhl</groupId>
    <artifactId>elasticsearch_demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>elasticsearch_demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring.data.elasticsearch.version>3.1.10.RELEASE</spring.data.elasticsearch.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.3.2</version>
            <exclusions>
                <!--这里内部依赖的版本太低,去除-->
                <exclusion>
                    <groupId>org.elasticsearch</groupId>
                    <artifactId>elasticsearch</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.elasticsearch.client</groupId>
                    <artifactId>elasticsearch-rest-client</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-client</artifactId>
            <version>7.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.60</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

然后看spring的代码,创建实体类Article

public class Article {
    private Integer id;
    private String title;
    private String content;
    private Date create_time;
    //省略getter & setter
}

创建一个RestHighLevelClient客户端的Bean,后面的操作都用这个Bean

@SpringBootApplication
public class ElasticsearchDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(ElasticsearchDemoApplication.class, args);
    }

    @Bean
    public RestHighLevelClient client() {
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("192.168.10.1", 9200, "http")));
        return client;
    }

}

下面的代码就是创建一个索引,对指定字段设置ik中文分词

    @Autowired
    RestHighLevelClient client;
   /**
     * 创建索引
     * 将实体类的String类型的字段添加ik中文分词,其他字段在实际添加数据后会按类型自动添加
     * @param clasz
     * @return
     */
    public Boolean createIndex2(Class clasz){
        try {
            CreateIndexRequest index = new CreateIndexRequest(clasz.getSimpleName().toLowerCase());

            XContentBuilder builder = JsonXContent.contentBuilder();
            builder.startObject()
                    .startObject("mappings")
                    .startObject("properties");
            Field[] fields = clasz.getDeclaredFields();
            for(Field field : fields){
                Class<?> type = field.getType();
                //这里只对String类型的字段添加ik中文分词处理
                if(type.getSimpleName().equals("String")){
                    builder.startObject(field.getName().toLowerCase())
                                .field("type","text")
                                .field("index",true)
                                .field("analyzer","ik_max_word")
                            .endObject();
                }
            }
            builder.endObject().endObject();
            builder.startObject("settings")
                    //分片数
                    .field("number_of_shards",1)
                    //副本数,1台机器设为0
                    .field("number_of_replicas",0)
                    .endObject()
                    .endObject();

            index.source(builder);
            CreateIndexResponse response = client.indices().create(index,RequestOptions.DEFAULT);
            log.info(JSONObject.toJSONString(response));
            return response.isAcknowledged();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 索引是否存在
     * @param indeces
     */
    public Boolean exist(String indeces){
        GetIndexRequest request = new GetIndexRequest(indeces.toLowerCase());
        Boolean exist = null;
        try {
            exist = client.indices().exists(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return exist;
    }

    /**
     * 删除索引
     * @param indeces
     */
    public void delete(String indeces){
        DeleteIndexRequest request = new DeleteIndexRequest(indeces.toLowerCase());
        try {
            AcknowledgedResponse deleteIndexResponse = client.indices().delete(request, RequestOptions.DEFAULT);
            boolean acknowledged = deleteIndexResponse.isAcknowledged();
            log.info("删除索引:{}", acknowledged);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 测试创建索引
     */
    @Test
    public void indexCreate(){
        Boolean exist = commodityServiceImpl.exist(Article.class.getSimpleName());
        if(!exist){
            log.info("需要创建新的索引");
            Boolean result = commodityServiceImpl.createIndex2(Article.class);
            log.info("创建索引结果:{}",result);
            return;
        }
        log.info("索引已存在,不需要创建新的");
    }

    /**
     * 删除索引
     */
    @Test
    public void indexDelete(){
        commodityServiceImpl.delete(Article.class.getSimpleName());
    }

运行测试代码,打开kibana,查看创建的索引http://localhost:5601/:

aticle就是前面创建的实体类的小写名称,mapping中的content字段和title是Article.class的两个String类型的成员,设置使用ik分词,其余没有设置的字段,会在添加数据后自动添加

 

除了用代码访问接口外,也可以使用kibana在Dev Tools使用创建mapping接口:

PUT article
{
  "mappings" : {
      "properties" : {
        "content" : {
          "type" : "text",
          "analyzer":"ik_max_word"
        },
        "title" : {
          "type" : "text",
          "analyzer":"ik_max_word"
        },
        "year" : {
          "type" : "long"
        }
      }
  }
}

用put 加 索引名称,json数据按照实际的实体类来修改即可。
 

 

 

我的DEMO项目下载:https://gitee.com/zhuhongliang/soringboot_elastic_search_732.git

要发表评论,您必须先登录