ElasticSearch使用二

1. ElasticSearch的java客户端

1.1 开发环境

jdk1.8
开发工具:idea
ElasticSearch

1.2 创建工程

1)创建一个maven工程,打包方式jar
2)添加jar包。添加jar包的坐标。
3)编写代码
Pom文件:

<dependencies>
    <dependency>
        <groupId>org.elasticsearch</groupId>
        <artifactId>elasticsearch</artifactId>
        <version>5.6.8</version>
    </dependency>
    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>transport</artifactId>
        <version>5.6.8</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-to-slf4j</artifactId>
        <version>2.9.1</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.24</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.7.21</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.12</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
</dependencies>

2. 索引库的管理

2.1 创建索引库

put方法
localhost:9200/{index}

2.1.1 步骤:

1、创建一个Settings对象,需要设置一个“cluster.name”属性
2、创建一个TransportClient对象,PreBuilderTransportClient类创建对象,需要Settings对象
3、向TransportClient对象中设置集群中的node列表
4、使用TransportClient创建索引库
5、关闭TransportClient对象

2.1.2 代码实现

@Test
public void createIndex() throws Exception {
    //1、创建一个Settings对象,需要设置一个“cluster.name”属性
    Settings settings = Settings.builder()
            .put("cluster.name", "my-elasticsearch")
            .build();
    //2、创建一个TransportClient对象,PreBuilderTransportClient类创建对象,需要Settings对象
    TransportClient client = new PreBuiltTransportClient(settings);
    //3、向TransportClient对象中设置集群中的node列表
    client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9301));
    client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9302));
    client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9303));
    //4、使用TransportClient创建索引库
    client.admin().indices()
            //设置索引库的名称
            .prepareCreate("blog")
            //执行操作
            .get();
    //5、关闭TransportClient对象
    client.close();
}

2.2 设置mapping信息

2.2.1 Json格式

使用postman设置mapping信息时的json格式:

创建索引库时直接设置mapping:
{
	"mappings":{
		"article":{
			"properties":{
				"id":{
					"type":"long",
					"index":true,
					"store":true
				},
				"title":{
					"type":"text",
					"store":true,
					"analyzer":"ik_max_word"
				},
				"content":{
					"type":"text",
					"store":true,
					"analyzer":"ik_max_word"
				}
			}
		}
	}
}
索引库存在之后设置mapping信息:
{
	"article":{
		"properties":{
			"id":{
				"type":"long",
				"index":true,
				"store":true
			},
			"title":{
				"type":"text",
				"store":true,
				"analyzer":"ik_max_word"
			},
			"content":{
				"type":"text",
				"store":true,
				"analyzer":"ik_max_word"
			}
		}
	}
}

可以使用XContentBuilder对象创建一个json对象。

2.2.2 步骤

1、创建一个TransportClient对象
2、创建一个XContentBuilder对象。创建一个json对象。
3、使用TransportClient对象将mapping信息设置到索引库上。
4、关闭TransportClient对象

2.2.3 代码实现

@Test
public void putMapping() throws Exception {
    Settings settings = Settings.builder()
            .put("cluster.name","my-elasticsearch")
            .build();
    TransportClient client = new PreBuiltTransportClient(settings)
            .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9301))
            .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9302))
            .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9303));
    //创建json对象
    /*{
        "article":{
        "properties":{
            "id":{
                "type":"long",
                        "index":true,
                        "store":true
            },
            "title":{
                "type":"text",
                        "store":true,
                        "analyzer":"ik_max_word"
            },
            "content":{
                "type":"text",
                        "store":true,
                        "analyzer":"ik_max_word"
            }
        }
    }
    }*/
    XContentBuilder builder = XContentFactory.jsonBuilder()
            .startObject()
                .startObject("article")
                    .startObject("properties")
                        .startObject("id")
                            .field("type", "long")
                            .field("index", true)
                            .field("store", "true")
                        .endObject()
                        .startObject("title")
                            .field("type", "text")
                            .field("store", "true")
                            .field("analyzer", "ik_max_word")
                        .endObject()
                        .startObject("content")
                            .field("type", "text")
                            .field("store", "true")
                            .field("analyzer", "ik_max_word")
                        .endObject()
                    .endObject()
                .endObject()
            .endObject();
    //使用client对象设置mapping信息
    client.admin().indices()
            //设置要向哪个索引库中设置mapping
            .preparePutMapping("blog")
            //设置mapping的type名称
            .setType("article")
            //设置mapping的json数据
            .setSource(builder)
            //执行操作
            .get();
    //关闭client
    client.close();



}

2.3 创建索引库时设置mapping信息

2.3.1 步骤

1、创建一个TransportClient对象
2、创建一个json对象,可以使用XContentBuilder,也可以直接使用字符串格式的json数据。
3、创建索引库,并且设置mapping信息。
4、关闭client

2.3.2 代码实现

@Test
public void createIndexWithMapping() throws Exception {
    String mapping = "{\n" +
            "\t\"mappings\":{\n" +
            "\t\t\"article\":{\n" +
            "\t\t\t\"properties\":{\n" +
            "\t\t\t\t\"id\":{\n" +
            "\t\t\t\t\t\"type\":\"long\",\n" +
            "\t\t\t\t\t\"index\":true,\n" +
            "\t\t\t\t\t\"store\":true\n" +
            "\t\t\t\t},\n" +
            "\t\t\t\t\"title\":{\n" +
            "\t\t\t\t\t\"type\":\"text\",\n" +
            "\t\t\t\t\t\"store\":true,\n" +
            "\t\t\t\t\t\"analyzer\":\"ik_max_word\"\n" +
            "\t\t\t\t},\n" +
            "\t\t\t\t\"content\":{\n" +
            "\t\t\t\t\t\"type\":\"text\",\n" +
            "\t\t\t\t\t\"store\":true,\n" +
            "\t\t\t\t\t\"analyzer\":\"ik_max_word\"\n" +
            "\t\t\t\t}\n" +
            "\t\t\t}\n" +
            "\t\t}\n" +
            "\t}\n" +
            "}";
    client.admin().indices()
            //新建索引库的名称
            .prepareCreate("blog2")
            //设置mapping信息
            .setSource(mapping, XContentType.JSON)
            .get();
    client.close();
}

2.4 删除索引库

2.4.1 步骤

1、创建一个TransportClient对象
2、使用TransportClient对象的prepareDelete方法删除索引库。
3、关闭client对象。

2.4.2 代码实现

@Test
public void deleteIndex() throws Exception {
    client.admin().indices()
            //指定要删除的索引库的名称
            .prepareDelete("hello")
            //执行操作
            .get();
    client.close();
}

3. 文档的管理

3.1 添加文档

向索引库中添加文档对象。还是json的数据格式。

3.1.1 步骤

1、创建一个TransportClient对象
2、创建一个文档对象使用json表示。
3、使用client对象向索引库中添加文档
4、关闭client

3.1.2 代码实现

@Test
public void addDocument() throws Exception {
    /*{
        "id":1,
            "title":"test title",
            "content":"document's content"
    }*/
    //创建一个文档对象,json格式,使用XContentBuilder创建
    XContentBuilder builder = XContentFactory.jsonBuilder()
            .startObject()
            .field("id", 1)
            .field("title","测试文档的标题")
            .field("content", "测试文档的内容")
            .endObject();
    //使用client对象将文档写入索引库
    client.prepareIndex()
            //.prepareIndex("blog", "article")
            //设置操作的索引库
            .setIndex("blog")
            //设置type名称
            .setType("article")
            //设置文档的id(_id)
            .setId("1")
            //设置文档信息
            .setSource(builder)
            //执行操作
            .get();
    //关闭
    client.close();
}

3.1.3 使用pojo对象转换成json

可以使用jackson工具包将java对象转换成json格式的字符串。Fastjson也可以。

3.1.3.1 添加jar包
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.8.1</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.1</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.8.1</version>
</dependency>

3.1.3.2 创建pojo类
public class Article {
    private long id;
    private String title;
    private String content;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

3.1.3.3 测试代码
@Test
public void addDocuemnt2() throws Exception {
    //创建一个Article对象
    Article article = new Article();
    //设置属性
    article.setId(2);
    article.setTitle("“2018年寿星榜”出炉:上海有2281名百岁老人");
    article.setContent("真格 “电商法”实施之后代购们该何去何从?");
    //将java对象转换成json格式的字符串
    //创建一个ObjectMapper对象
    ObjectMapper objectMapper = new ObjectMapper();
    //使用Objectmapper对象将java对象转换成json字符串
    String json = objectMapper.writeValueAsString(article);
    //使用client对象将文档写入索引库
    client.prepareIndex("blog", "article", "2")
            .setSource(json, XContentType.JSON)
            .get();
    //关闭client
    client.close();
}

3.2 删除文档

3.2.1 步骤

1、创建一个TransportClient对象
2、使用client的prepareDelete方法根据id删除文档
3、关闭client对象

3.2.2 测试代码

@Test
public void deleteDocument() throws Exception {
    client.prepareDelete("blog", "article", "1")
            //执行操作
            .get();
    client.close();
}

3.3 修改文档

Es的底层是lucene,lucene更新的原理是先删除后添加。ES中也是先删除后添加。可以根据_id进行文档的更新。

3.3.1 实现步骤

1、创建TransportClient对象
2、创建一个Document对象(json格式)
3、向索引库中添加json格式的文档
跟向索引库中添加文档是一样的,只要新添加的文档和被更新的文档id一致即可。

3.3.2 测试代码

@Test
public void updateDocument() throws Exception {
    //创建一个Article对象
    Article article = new Article();
    //设置属性
    article.setId(2);
    article.setTitle("“2018年寿星榜”出炉:上海有2281名百岁老人33333");
    article.setContent("真格 “电商法”实施之后代购们该何去何从?222222222222222222");
    //将java对象转换成json格式的字符串
    //创建一个ObjectMapper对象
    ObjectMapper objectMapper = new ObjectMapper();
    //使用Objectmapper对象将java对象转换成json字符串
    String json = objectMapper.writeValueAsString(article);
    //更新数据
    /*client.prepareIndex("blog","article", "2")
            .setSource(json, XContentType.JSON)
            .get();*/
    client.prepareUpdate("blog", "article", "2")
            .setDoc(json, XContentType.JSON)
            .get();
    client.close();
}

3.4 文档的查询

3.4.1 实现步骤

1、创建一个client对象
2、创建QueryBuilder查询对象
3、使用client的prepareQuery方法,执行查询
4、取查询结果
5、可以取查询结果的总记录数
6、取结果列表
7、关闭client

3.4.2 根据id查询

创建一个根据id查询的QueryBuilder对象

@Test
public void searchById() throws Exception {
    //1、创建一个client对象
    //2、创建QueryBuilder查询对象
    QueryBuilder builder = QueryBuilders.idsQuery()
            .addIds("2");
    //3、使用client的prepareQuery方法,执行查询
    //设置查询的索引库
    SearchResponse searchResponse = client.prepareSearch("blog")
            //设置查询的type
            .setTypes("article")
            //设置查询条件
            .setQuery(builder)
            //执行查询
            .get();
    //4、取查询结果
    SearchHits searchHits = searchResponse.getHits();
    //5、可以取查询结果的总记录数
    System.out.println("查询结果的总记录数:" + searchHits.getTotalHits());
    //6、取结果列表
    SearchHit[] hits = searchHits.getHits();
    for (SearchHit hit : hits) {
        Map<String, Object> source = hit.getSource();
        System.out.println(source);
    }
    //7、关闭client
    client.close();
}

3.4.3 TermQuery根据关键词查询

@Test
public void searchByTerm() throws Exception {
    //1、创建一个client对象
    //2、创建QueryBuilder查询对象
    //参数1:要查询的域 参数2:要查询的关键词
    QueryBuilder builder = QueryBuilders.termQuery("title", "寿星老");
    //3、使用client的prepareQuery方法,执行查询
    //设置查询的索引库
    SearchResponse searchResponse = client.prepareSearch("blog")
            //设置查询的type
            .setTypes("article")
            //设置查询条件
            .setQuery(builder)
            //执行查询
            .get();
    //4、取查询结果
    SearchHits searchHits = searchResponse.getHits();
    //5、可以取查询结果的总记录数
    System.out.println("查询结果的总记录数:" + searchHits.getTotalHits());
    //6、取结果列表
    SearchHit[] hits = searchHits.getHits();

    for (SearchHit hit : hits) {
        //获得返回的文档对象,使用map表示
        Map<String, Object> source = hit.getSource();
        System.out.println(source);
    }
    //7、关闭client
    client.close();
}

3.4.4 QueryString查询

查询方法同上,不同之处就是QueryBuilder不同。

QueryBuilder builder = QueryBuilders.queryStringQuery("央行连续11日暂停公开市场操作").defaultField("title");

3.5 查询的分页处理

3.5.1 使用方法

在使用ES的查询时,默认是进行分页处理每页默认显示的是10条数据。
设置分页信息需要在parePareSearch方法调用之后设置分页信息。
需要设置两个参数:
from:起始的行号,默认是0
size:每页显示的记录数,默认是10
类似于mysql中的分页。

3.5.2 代码实现

@Test
public void searchByTermWithPage() throws Exception {
    //1、创建一个client对象
    //2、创建QueryBuilder查询对象
    //参数1:要查询的域 参数2:要查询的关键词
    QueryBuilder builder = QueryBuilders.termQuery("title", "人民币");
    //参数:要查询的条件,可以是一句话
    //QueryBuilder builder = QueryBuilders.queryStringQuery("央行连续11日暂停公开市场操作").defaultField("title");
    //3、使用client的prepareQuery方法,执行查询
    //设置查询的索引库
    SearchResponse searchResponse = client.prepareSearch("blog")
            //设置查询的type
            .setTypes("article")
            //设置查询条件
            .setQuery(builder)
            //设置分页信息,起始的行号
            .setFrom(0)
            //每页显示的行数
            .setSize(3)
            //执行查询
            .get();
    //4、取查询结果
    SearchHits searchHits = searchResponse.getHits();
    //5、可以取查询结果的总记录数
    System.out.println("查询结果的总记录数:" + searchHits.getTotalHits());
    //6、取结果列表
    SearchHit[] hits = searchHits.getHits();

    for (SearchHit hit : hits) {
        //获得返回的文档对象,使用map表示
        Map<String, Object> source = hit.getSource();
        System.out.println(source);
    }
    //7、关闭client
    client.close();
}

3.6 高亮显示

原理:在关键词前后分别添加一个前缀和后缀,在页面中显示时让其醒目突出即可。

3.6.1 使用方法

1、在执行查询之前,需要设置高亮显示,在调用prepareSearch方法之后设置高亮信息。
需要设置三个属性:
1)设置高亮显示的域的名称
2)设置高亮显示的前缀
3)设置高亮显示的后缀
2、取结果时,不仅可以取出返回的文档对象还可以取高亮的结果。

3.6.2 测试代码

@Test
public void searchByTermWithHighlighing() throws Exception {
    //1、创建一个client对象
    //2、创建QueryBuilder查询对象
    //参数1:要查询的域 参数2:要查询的关键词
    QueryBuilder builder = QueryBuilders.termQuery("title", "人民币");
    //参数:要查询的条件,可以是一句话
    //QueryBuilder builder = QueryBuilders.queryStringQuery("央行连续11日暂停公开市场操作").defaultField("title");
    //3、使用client的prepareQuery方法,执行查询
    //创建高亮显示的Builder对象
    HighlightBuilder highlightBuilder = new HighlightBuilder()
            //设置高亮显示的域
            .field("title")
            //前缀
            .preTags("<em>")
            //后缀
            .postTags("</em>");
    //设置查询的索引库
    SearchResponse searchResponse = client.prepareSearch("blog")
            //设置查询的type
            .setTypes("article")
            //设置查询条件
            .setQuery(builder)
            //设置分页信息,起始的行号
            .setFrom(0)
            //每页显示的行数
            .setSize(3)
            //设置高亮信息
            .highlighter(highlightBuilder)
            //执行查询
            .get();
    //4、取查询结果
    SearchHits searchHits = searchResponse.getHits();
    //5、可以取查询结果的总记录数
    System.out.println("查询结果的总记录数:" + searchHits.getTotalHits());
    //6、取结果列表
    SearchHit[] hits = searchHits.getHits();

    for (SearchHit hit : hits) {
        //获得返回的文档对象,使用map表示
        Map<String, Object> source = hit.getSource();
        //当前文档对象高亮的结果
        Map<String, HighlightField> highlightFields = hit.getHighlightFields();
        System.out.println(source);
        System.out.println(highlightFields);
        //根据高亮显示的域的名称取结果
        Text title = highlightFields.get("title").getFragments()[0];
        System.out.println(title);
    }
    //7、关闭client
    client.close();
}

3.7 查询小结

查询:
1、查询条件
(1)根据id查询
(2)根据Term查询
(3)根据QueryString查询

2、分页条件
应该看做的查询条件之一。

3、高亮条件
应该是查条件之一。
需要设置高亮显示的域
高亮显示的前缀
高亮显示的后缀

返回结果:
1、查询结果总记录数:totalHits属性
2、查询结果
SearchHit[]:结果数组
SearchHit结果中的一个元素。
1)其中source属性文档对象。使用map表示。无论是否开启高亮字段中的内容不会发生变化。
2)其中highlightFields属性就是高亮的处理结果。开启高亮之后其中就有内容。
可以从highlightFields对象中取高亮的结果。
设置哪个域就有哪个域的高亮结果。

4. SpringDataElasticSearch框架

4.1 简介

SpringData项目中的一个子项目。把ElasticSearch的API进一步封装。使用更简单方便。
使用原生api可以实现的功能SpringDataElasticSearch都可以实现。

4.2 创建工程

把ElasticSearch和spring整合使用。
1、创建一个maven工程
2、把需要的jar包添加到工程中。
3、创建一个applicationContext.xml配置文件将spring和SpringDataElasticSearch整合。

4.2.1 Pom文件

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.itheima</groupId>
    <artifactId>springdata-es</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>5.6.8</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>5.6.8</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-to-slf4j</artifactId>
            <version>2.9.1</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.24</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.21</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>


        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.8.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.8.1</version>
        </dependency>


        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-elasticsearch</artifactId>
            <version>3.0.5.RELEASE</version>
            <exclusions>
                <exclusion>
                    <groupId>org.elasticsearch.plugin</groupId>
                    <artifactId>transport-netty4-client</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.4.RELEASE</version>
        </dependency>

    </dependencies>
    
</project>

4.2.2 applicationContext.xml

1、其中配置TransportClient对象,在系统中应该是单例存在的。
2、还需要配置一个ElasticSearchTemplate对象

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"
       xsi:schemaLocation="
      http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd
      http://www.springframework.org/schema/data/elasticsearch
      http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd">

    <elasticsearch:transport-client id="client"
                                    cluster-name="my-elasticsearch"
                                    cluster-nodes="127.0.0.1:9301,127.0.0.1:9302,127.0.0.1:9303"/>
    <bean id="elasticSearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
        <constructor-arg name="client" ref="client"/>
    </bean>
</beans>

4.3 索引库操作

4.3.1 创建索引库

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SprintDataElasticSearchTest {

    @Autowired
    private ElasticsearchTemplate template;

    @Test
    public void createIndex() throws Exception {
        template.createIndex("blog3");
    }

}

4.3.2 设置mapping信息

创建一个Entity类,对应索引库中的type。配置Entity的属性和索引库中的字段的映射关系。

4.3.2.1 实体类
@Document(indexName = "blog3", type = "article")
public class Article {
    @Id
    @Field(type = FieldType.Long, store = true)
    private long id;
    @Field(type = FieldType.text, store = true, analyzer = "ik_max_word")
    private String title;
    @Field(type = FieldType.text, store = true, analyzer = "ik_max_word")
    private String content;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    @Override
    public String toString() {
        return "Article{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", content='" + content + '\'' +
                '}';
    }
}

4.3.2.2 测试代码
@Test
public void putMapping() throws Exception {
    template.putMapping(Article.class);
}

4.3.3 创建索引库并设置mapping

@Test
public void createIndexWithMapping() {
    template.createIndex(Article.class);
    template.putMapping(Article.class);
}

4.4 删除索引库

@Test
public void deleteIndex() {
    template.deleteIndex(Article.class);
    template.deleteIndex("blog2");
}

4.5 文档的操作

4.5.1 添加文档

直接使用Article类创建一个文档对象。创建一个Dao接口需要继承ElasticSearchRepository接口。就有增删改查的方法。

4.5.1.1 Dao
public interface ArticleDao extends ElasticsearchRepository<Article, Long> {
}

4.5.1.2 applicationContext.xml

添加一个dao 的包扫描器。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"
       xsi:schemaLocation="
      http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd
      http://www.springframework.org/schema/data/elasticsearch
      http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd">

    <elasticsearch:transport-client id="client"
                                    cluster-name="my-elasticsearch"
                                    cluster-nodes="127.0.0.1:9301,127.0.0.1:9302,127.0.0.1:9303"/>
    <bean id="elasticSearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
        <constructor-arg name="client" ref="client"/>
    </bean>
    <!--dao的扫描器-->
    <elasticsearch:repositories base-package="com.itheima.reopstory"/>
    
</beans>

4.5.1.3 测试代码
@Test
public void addDocuemnt() {
    //创建一个Article对象
    Article article = new Article();
    article.setId(1);
    article.setTitle("测试文档");
    article.setContent("测试文档的内容");
    //写入索引库
    articleDao.save(article);

}

4.5.2 删除文档

@Test
public void deleteDocument() {
    articleDao.deleteById(1l);
}

4.5.3 修改文档

@Test
public void updateDocumeent() {
    Optional<Article> optional = articleDao.findById(1l);
    Article article = optional.get();
    article.setTitle("女子网恋被骗168万 对方自称在迪拜经商美国男子");
    articleDao.save(article);
}

4.5.4 查询文档

4.5.4.1 根据id查询

4.5.5 根据方法命名规则查询

相当于根据term查询。

关键字命名规则解释示例
andfindByField1AndField2findByField1AndField2 根据Field1和Field2获得数据findByTitleAndContent
orfindByField1OrField2根据Field1或Field2获得数据findByTitleOrContent
isfindByField根据Field获得数据findByTitle
notfindByFieldNot根据Field获得补集数据findByTitleNot
betweenfindByFieldBetween获得指定范围的数据findByPriceBetween
lessThanEqualfindByFieldLessThan获得小于等于指定值的数据findByPriceLessThan
4.5.5.1 Dao
public interface ArticleDao extends ElasticsearchRepository<Article, Long> {
    Article getById(long id);
    List<Article> findByTitle(String title);
}

4.5.5.2 测试方法
@Test
public void testMethod() {
    Article article = articleDao.getById(1);
    System.out.println(article);
    List<Article> list = articleDao.findByTitle("迪拜");
    for (Article article1 : list) {
        System.out.println(article1);
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 Elasticsearch SQL 插件,您需要先确保您已经安装了 Elasticsearch 7.1.1 版本。然后,按照以下步骤进行操作: 1. 安装 Elasticsearch SQL 插件: - 打开终端或命令提示符窗口。 - 运行以下命令安装 Elasticsearch SQL 插件: ``` ./bin/elasticsearch-plugin install https://github.com/NLPchina/elasticsearch-sql/releases/download/7.1.1.0/elasticsearch-sql-7.1.1.0.zip ``` - 安装完成后,重启 Elasticsearch 以使插件生效。 2. 使用 Elasticsearch SQL: - 打开终端或命令提示符窗口。 - 进入 Elasticsearch 的安装目录。 - 运行以下命令以启动 Elasticsearch SQL 查询: ``` ./bin/elasticsearch-sql-cli ``` - 您将进入 Elasticsearch SQL 的命令行界面。 - 现在,您可以开始使用 SQL 语法来查询 Elasticsearch 据。 例如,您可以运行以下命令来执行一个简单的 SELECT 查询: ``` SELECT * FROM your_index_name WHERE your_field_name = 'your_value' ``` 注意:在上述查询中,`your_index_name` 是您要查询的索引名称,`your_field_name` 是您要查询的字段名称,`your_value` 是您要匹配的字段值。 这样,您就可以使用 Elasticsearch SQL 插件来执行 SQL 查询并检索 Elasticsearch 中的据了。请记住,Elasticsearch SQL 插件提供了一种方便的方式来使用 SQL 语法进行查询,但它可能不适用于所有类型的查询,特别是复杂的查询。因此,在使用插件时,请确保您了解其使用限制和适用场景。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值