ElasticSearch 安装,保存,查询,更新,复杂查询,模糊查询,高亮查询

news2024/11/16 10:22:48

ElasticSearch

ik分词器:

ik分词器的安装,将ik分词器下载并解压,新建文件夹ik,将解压内容放进ik文件夹中,将ik文件夹放在es安装路径的plugin文件夹中

GET _analyze
{
  "analyzer": "ik_smart",
  "text":"中国共产党"
}

GET _analyze
{
  "analyzer": "ik_max_word",
  "text":"中国共产党"
}

ik_smart:最小切片划分
ik_max_word:最细粒度划分

ik分词器增加自己的配置

在es的安装目录中/elasticsearch/plugins/ik/config,创建后缀名为.dic的文件,将自己配置的词语写到.dic文件中,

文件中的内容:

在这里插入图片描述

docker下安装Elasticsearch和kibana

1、将云端镜像拉取到本地:

docker pull elasticsearch

2、安装elasticsearch

docker run -it --name elasticsearch -d -p 9200:9200 -p 9300:9300 -p 5601:5601 elasticsearch

docker run -id --name es -p 9200:9200 -p 9300:9300 -e “discovery.type=single-node”
elasticsearch:7.4.0

3、将kibana从云端拉取到本地

docker pull kibana

4、安装kibana

docker run -it -d -e ELASTICSEARCH_URL=http://192.168.58.20:9200 --name kibana --network=container:elasticsearch kibanadocker run -it -d -e ELASTICSEARCH_URL=http://192.168.58.20:9200 --name kibana --network=container:elasticsearch kibana

docker run -id --name kibana --link es:elasticsearch -p 5601:5601 kibana:7.4.0

一、初步检索

1、保存文档

PUT testdb  //创建索引,未添加值
{
  "mappings":{
    "properties": {
      "name":{
        "type":"text"
      },
      "desc":{
        "type":"keyword"
      }
    }
  }
}
PUT /human/user/1
{
  "name":"tfxing",
  "age":18,
  "desc":"优秀的中国五四好青年"
}

2、查询数据

GET /human/user/1
GET human/user/_search?q=name:tfxing

##################
{
  "_index" : "human",
  "_type" : "user",
  "_id" : "1",
  "_version" : 1,
  "_seq_no" : 0,
  "_primary_term" : 1,
  "found" : true,
  "_source" : {
    "name" : "tfxing",
    "age" : 18,
    "desc" : "优秀的中国五四好青年"
  }
} 

3、更新文档

3.1、put更新会将没有更新值的字段去除,只要执行了,_version就会更新
3.2、post更新只会更新写了的字段,没写的字段会保存原来的值,post修改如果字段没有变的会,_version不会更新
PUT human/user/1
{
  "name":"tfxing",
  "age":20
}


############################
{
  "_index" : "human",
  "_type" : "user",
  "_id" : "1",
  "_version" : 2,
  "_seq_no" : 1,
  "_primary_term" : 1,
  "found" : true,
  "_source" : {
    "name" : "tfxing",
    "age" : 20
  }
} 
POST human/user/2/_update
{
  "doc": {
    "name":"zxyan",
    "age":19
  }
}


//--------------愿来的值----------
{
  "_index" : "human",
  "_type" : "user",
  "_id" : "2",
  "_version" : 1,
  "_seq_no" : 2,
  "_primary_term" : 1,
  "found" : true,
  "_source" : {
    "name" : "zxyan",
    "age" : 18,
    "desc" : "优秀的中国五四好青年"
  }
}

//---------------修改后的值-----------

 {
  "_index" : "human",
  "_type" : "user",
  "_id" : "2",
  "_version" : 4,
  "_seq_no" : 5,
  "_primary_term" : 1,
  "found" : true,
  "_source" : {
    "name" : "zxyan",
    "age" : 19,
    "desc" : "优秀的中国五四好青年"
  }
}

4、复杂查询

内嵌结构

在这里插入图片描述

4.1、字段过滤(_source)
GET human/user/_search
{
  "query":{
    "match":{  //match:模糊查询
      "name":"tfxing"
    }
  },
  "_source":["name"]
}

GET human/user/_search
{
  "query":{
    "match":{
      "name":"tfxing"
    }
  },
  "_source":["name","age"]
}
#######查询结果########
{
  "took" : 3,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 1.4599355,
    "hits" : [
      {
        "_index" : "human",
        "_type" : "user",
        "_id" : "1",
        "_score" : 1.4599355,
        "_source" : {
          "name" : "tfxing"
        }
      }
    ]
  }
}
 
4.2、排序(sort)
GET human/user/_search
{
  "_source":["name","age"],
  "sort":[
    {
      "age":{
        "order":"asc"  //按age升序排序,desc:降序
      }
    }
  ]
}

#####查询结果######

 
4.3、分页(from , size)从第几个数据开始查,返回多少条数据,索引下标从0开始
GET human/user/_search
{
  "_source":["name","age"],
  "sort":[
    {
      "age":{
        "order":"asc"
      }
    }
  ],
  "from":0,
  "size":2
}
4.4、布尔查询(bool):多条件查询
must(and),所有条件都要符合,相当于sql中的and

should(or),

GET human/user/_search
{
  "query":{
    "bool":{
      "must":[
          {
            "match":{
              "name":"tfxing"
            }
          },
          {
            "match":{
              "age":20
            }
          }
        ]
    }
  }
}
should:等价与sql中的or,条件中满足一个即可
GET human/user/_search
{
  "query":{
    "bool":{
      "should":[
          {
            "match":{
              "name":"tfxing"
            }
          },
          {
            "match":{
              "age":18
            }
          }
        ]
    }
  }
}

########结果集######
#! Deprecation: [types removal] Specifying types in search requests is deprecated.
{
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 2,
      "relation" : "eq"
    },
    "max_score" : 1.4599355,
    "hits" : [
      {
        "_index" : "human",
        "_type" : "user",
        "_id" : "1",
        "_score" : 1.4599355,
        "_source" : {
          "name" : "tfxing",
          "age" : 20
        }
      },
      {
        "_index" : "human",
        "_type" : "user",
        "_id" : "2",
        "_score" : 1.0,
        "_source" : {
          "name" : "zxyan",
          "age" : 18,
          "desc" : "优秀的中国五四好青年"
        }
      }
    ]
  }
}
 
must_not:不满足
GET human/user/_search
{
  "query":{
    "bool":{
      "must_not":[
          {
            "match":{
              "name":"tfxing"
            }
          },
          {
            "match":{
              "age":20
            }
          }
        ]
    }
  }
}
4.5、过滤查询(range) gt:大于、gte:大于等于、lt:小于、lte:小于等于
GET human/user/_search
{
  "query":{
    "bool":{
      "must":[
        {
          "match":{
            "name":"张三"
          }
        }
      ],
      "filter":{
        "range":{
          "age":{
            "gte":22  //gt:大于、gte:大于等于、lt:小于、lte:小于等于
          }
        }
      }
    }
  }
}

4.6、模糊查询(match)多个条件使用空格隔开

只要满足其一就能被查询出来

GET human/user/_search
{
  "query":{
    "match":{
      "desc":"优秀 法外"
    }
  }
}

4.7、通过倒排索引指定的词条进行精确查询(term)

term:直接查询精确的

match:会使用分词器解析,(先分析文档,然后通过分析的文档进行查询)

keyword字段类型不会被分词器解析
GET human/user/_search
{
  "query":{
    "bool":{
      "should":[
          {
            "match":{
              "name":"tfxing"
            }
          },
          {
            "match":{
              "name":"zxyan"
            }
          }
        ]
    }
  }
}
4.8、高亮查询

搜索相关的结果可以高亮显示

GET human/user/_search
{
  "query":{
    "match":{
      "name":"tfxing"
    }
  },
  "highlight":{
    "pre_tags":"<p class='key' style='color:red'>",  //搜索结果前缀  自定义搜索条件
    "post_tags":"</p>",  //后缀
    "fields":{
      "name":{}
    }
  }
}


#######查询结果#######
#! Deprecation: [types removal] Specifying types in search requests is deprecated.
{
  "took" : 2,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 1.4599355,
    "hits" : [
      {
        "_index" : "human",
        "_type" : "user",
        "_id" : "1",
        "_score" : 1.4599355,
        "_source" : {
          "name" : "tfxing",
          "age" : 20
        },
        "highlight" : {
          "name" : [
            "<p class='key' style='color:red'>tfxing</p>"
          ]
        }
      }
    ]
  }
}
 

二、ES继承springboot

1、导入pom依赖
<!--引入es的坐标-->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-client</artifactId>
            <version>7.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.4.0</version>
        </dependency>

1、_cat(带_的都叫元数据)

GET/_cat/nodes: 查看所有节点

GET/_cat/health: 查看es健康状况

GET/_cat/master: 查看主节点

GET/_cat/indices:查看所有索引(类似show databases)

2、索引一个文档(保存)

保存一个数据,保存在那个索引的哪个类型下

PUT/customer/external/1

例:PUT http://192.168.58.20:9200/customer/external/1 { “name”:“tfxing”}

发送多次为更新,使用put和post都可以,如果不指定id,会生成一个随机id

3、查询文档

GET customer/external

在这里插入图片描述

4、更新文档

在这里插入图片描述

post加_update的方式会对比原来的数据,如果没有改变,则_sql_no和_version不会改变

注意:使用post加_update的方式更新需要加上"doc":{“name”:“tfxing”},需要加doc,而put和post不带_update则不需要加doc

而put和post不带_update更新不会对比原来的数据,_ sql_no和_version会改变

在这里插入图片描述

5、删除文档&索引

在这里插入图片描述

删除指定文档和删除整个索引(整个表)

6、bulk批量API

在这里插入图片描述

在这里插入图片描述

post请求,一个大括号代表一个索引,两行为一个整体,

delete删除没有请求体,所以只有一行

create:创建,title行为创建的数据

index:保存,title行为需要保存的数据

update:更新,“_retry_on_conflict”:3:表示如果更新失败,重试3次

在这里插入图片描述

二、MatchAll查询流程

 @Test
    public void matchAll() throws Exception{
        //2.构建查询请求对象,指定查询的索引名称
        SearchRequest searchRequest = new SearchRequest("goods");
/*
        3.添加查询条件构建器 SearchSourceBuilder,
        4.创建查询条件构建起SearchSourceBuilder,
        5.指定查询条件,
        6.查询条件
*/
        searchRequest.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));

        //1.查询,获取查询结果
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        //7.获取Hits数据 数组
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            Goods goods = JSON.parseObject(hit.getSourceAsString(), Goods.class);
            System.out.println(goods);
        }
    }
    

1、开发流程:

1.1、创建moudle
2.2、导入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>
    <artifactId>spiringbootEs</artifactId>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>


    <properties>
        <!--<mysql.version>8.0.18</mysql.version>-->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
    
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
            <version>1.16.18</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--引入es的坐标-->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-client</artifactId>
            <version>7.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.4.0</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.4</version>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>
</project>
1.3、yml配置
elasticsearch:
  host: 192.168.58.20
  port: 9200
spring:
  datasource:
    url: jdbc:mysql:///elasticsearch?serverTimezone=UTC
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
  mapper-locations:classpath: com/tfxing/mapper/*Mapper.xml
  type-aliases-package: com.tfxing.bean

集群用逗号隔开

在这里插入图片描述

1.4、编写主启动类
package com.tfxing;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

1.5、编写实体类
package com.tfxing.bean;

import java.util.Date;
import java.util.Map;

@Data
public class Goods {
    private int id;
    private String title;
    private double price;
    private int stock;
    private int saleNum;
    private Date createTime;
    private String categoryName;
    private String brandName;
    private Map spec;
    private String specStr;
}

1.6、编写config类
package com.tfxing.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConfigurationProperties(prefix = "elasticsearch")
public class ESConfig {
    private String host;
    private int port;

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    @Bean
    public RestHighLevelClient client(){
        return new RestHighLevelClient(RestClient.builder(
                new HttpHost(
                        host,
                        port,
                        "http"
                )
        ));
    }
}

1.7、编写mapper层
package com.tfxing.mapper;

import com.tfxing.bean.Goods;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface GoodsMapper {
    List<Goods> findAll();
}

<?xml version="1.0" encoding="UTF-8" ?>
        <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.tfxing.mapper.GoodsMapper">

    <select id="findAll" resultType="goods">
        select
              `id`         ,
              `title`       ,
              `price`       ,
              `stock`       ,
              `saleNum`     ,
              `createTime`  ,
              `categoryName`,
              `brandName`   ,
              `spec`  as specStr

         from goods

    </select>

</mapper>


1.8、测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestES {
    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private GoodsMapper goodsMapper;

    @Test
    public void testClient(){
        System.out.println(client);
    }

} 

三、各类功能的实现

1、创建索引

    /**
     * 创建索引
     */
    @Test
    public void addIndices() throws Exception{
        //1.使用client获取操作索引的对象
        IndicesClient indices = client.indices();
        //2.具体操作,获取返回值,teacher参数相当于es的表名
        CreateIndexRequest request = new CreateIndexRequest("teacher");
        CreateIndexResponse response = indices.create(request, RequestOptions.DEFAULT);
        //3.根据返回值判断是否成功上面的操作
        System.out.println(response.isAcknowledged());
    }

2、添加索引和映射

/**
     * 添加索引和映射
     */
    @Test
    public void addIndicesAndMapping() throws Exception{
        //1.使用client获取操作索引的对象
        IndicesClient indices = client.indices();
        //2.具体操作,并取得返回值,使用indices.create()方法,需要传入一个CreateIndexRequst和一个指令对象RequstOptions
        CreateIndexRequest indexRequest = new CreateIndexRequest("student");
        //2.1、设置mappings
        String mapping = "{\n" +
                "      \"properties\" : {\n" +
                "        \"address\" : {\n" +
                "          \"type\" : \"text\",\n" +
                "          \"analyzer\" : \"ik_max_word\"\n" +
                "        },\n" +
                "        \"age\" : {\n" +
                "          \"type\" : \"long\"\n" +
                "        },\n" +
                "        \"name\" : {\n" +
                "          \"type\" : \"keyword\"\n" +
                "        }\n" +
                "      }\n" +
                "    }";
        indexRequest.mapping(mapping, XContentType.JSON);
        //3、根据返回值判断是否成功执行
        CreateIndexResponse response = indices.create(indexRequest, RequestOptions.DEFAULT);
        System.out.println(response.isAcknowledged());
    }

3、查询索引

/**
     * 查询索引
     */
    @Test
    public void queryIndex() throws Exception{
        IndicesClient indices = client.indices();
        GetIndexResponse response = indices.get(new GetIndexRequest("student"), RequestOptions.DEFAULT);
        //获取结果
        Map<String, MappingMetaData> mappings = response.getMappings();
        for (String key : mappings.keySet()) {
            System.out.println(key + ":" + mappings.get(key).getSourceAsMap());
        }
    }

4、删除索引

/**
     * 删除索引
     */
    @Test
    public void testDelete() throws Exception{
        IndicesClient indices = client.indices();
        AcknowledgedResponse response = indices.delete(new DeleteIndexRequest("teacher"), RequestOptions.DEFAULT);
        System.out.println(response.isAcknowledged());
    }

5、判断索引是否存在

   /**
     * 判断索引是否存在
     */
    @Test
    public void testExistIndex() throws Exception{
        IndicesClient indices = client.indices();
        boolean exists = indices.exists(new GetIndexRequest("person"), RequestOptions.DEFAULT);
        System.out.println(exists);
    }

6、添加文档,使用map作为数据

   /**
     * 添加文档,使用map作为数据
     */
    @Test
    public void addDocByMap() throws Exception{
        //数据对象
        Map data = new HashMap();
        data.put("address","深圳宝安");
        data.put("name","tfxing");
        data.put("age",18);

        //1.获取操作文档的对象
        IndexRequest request = new IndexRequest("student").id("1").source(data);
        //2.添加数据,获取结果
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);

        System.out.println(response.getId());
    }

7、添加文档,使用对象作为数据

/**
     * 使用对象进行添加操作
     * @throws Exception
     */
    @Test
    public void addDocByPojo() throws Exception{
        Student student = new Student("2","laow",19,"江西赣州");

        //将对象转换成json数据
        String studentJson = JSON.toJSONString(student);
        //获取操作文档的对象
        IndexResponse response = client.index(new IndexRequest("student").id(student.getId()).source(studentJson,XContentType.JSON), RequestOptions.DEFAULT);
        System.out.println(response.getId());
    }

8、修改文档


    /**
     * 修改文档
     */
    @Test
    public void updateDoc() throws Exception{
        Student student = new Student("2","lwang",19,"江西赣州");

        //将对象转换成json数据
        String studentJson = JSON.toJSONString(student);
        //获取操作文档的对象
        IndexResponse response = client.index(new IndexRequest("student").id(student.getId()).source(studentJson,XContentType.JSON), RequestOptions.DEFAULT);
        System.out.println(response.getId());
    }

9、根据id查询文档

/**
     * 根据id查询文档
     */
    @Test
    public void findById() throws Exception{
        GetResponse response = client.get
        (new GetRequest("student", "1")
        , RequestOptions.DEFAULT);
        Map<String, Object> source = response.getSourceAsMap();
        System.out.println(source);
    }

10、根据id删除文档

 /**
     * 根据id删除文档
     */
    @Test
    public void delDoc() throws Exception{
        DeleteResponse response = client.delete(new DeleteRequest("student", "1"), RequestOptions.DEFAULT);
        System.out.println(response.status());
    }

11、测试term条件查询

/**
     *测试term条件查询
     */
    @Test
    public void term() throws Exception{
        SearchRequest searchRequest = new SearchRequest("student");
        searchRequest.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("address", "江西深圳")));
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);

        SearchHits hits = response.getHits();
        SearchHit[] hits1 = hits.getHits();
        for (SearchHit hit : hits1) {
            String sourceAsString = hit.getSourceAsString();
            Student student = JSON.parseObject(sourceAsString,Student.class);
            System.out.println(student);
        }
    }

返回结果

在这里插入图片描述

12、测试Operator查询

/**
     * 测试Operator查询
     */
    @Test
    public void test1() throws Exception{
        SearchRequest searchRequest = new SearchRequest("student");
        searchRequest.source(new SearchSourceBuilder().query(QueryBuilders.matchQuery("address","江西深圳").operator(Operator.OR)));
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHit[] hits1 = response.getHits().getHits();
        for (SearchHit hit : hits1) {
            String sourceAsString = hit.getSourceAsString();
            Student student = JSON.parseObject(sourceAsString,Student.class);
            System.out.println(student);
        }
    }

13、批量操作

/**
     * 批量操作
     */
    @Test
    public void bluk() throws Exception{
        //1.创建bulkRequst对象,整合所有操作
        BulkRequest bulkRequest = new BulkRequest();
        //添加对应的操作

        //删除一条数据
        bulkRequest.add(new DeleteRequest("student","1"));

        //添加一条数据
        String aJsonStr = JSON.toJSONString(new Student("3", "aaa", 20, "北京昌平"));
        IndexRequest indexStudenta = new IndexRequest("student").id("3").source(aJsonStr, XContentType.JSON);
        bulkRequest.add(indexStudenta);

        //添加一条数据
        IndexRequest indexRequest = new IndexRequest("student").id("4").source(JSON.toJSONString(new Student("4", "bbb", 21, "上海")), XContentType.JSON);
        bulkRequest.add(indexRequest);

        //执行操作,并判断是否执行成功
        BulkResponse bulk = client.bulk(bulkRequest,RequestOptions.DEFAULT);
        System.out.println(bulk.status());
    }

14、导入数据

/**
     * 导入数据
     */
    @Test
    public void insetData() throws Exception{
        List<Goods> goodsList = goodsMapper.findAll();
        BulkRequest bulkRequest = new BulkRequest();
        for (Goods goods : goodsList) {
            Map map = JSON.parseObject(goods.getSpecStr(), Map.class);
            goods.setSpec(map);
            String goodsJsonStr = JSON.toJSONString(goods);
            IndexRequest indexRequest = new IndexRequest("goods").id(goods.getId() + "").source(goodsJsonStr, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(bulk.status());
    }

15、使用matchAll查询

/**
     * 使用matchAll查询
     */
    @Test
    public void matchAll() throws Exception{
        //2.构建查询请求对象,指定查询的索引名称
        SearchRequest searchRequest = new SearchRequest("goods");
/*
        3.添加查询条件构建器 SearchSourceBuilder,
        4.创建查询条件构建起SearchSourceBuilder,
        5.指定查询条件,
        6.查询条件
*/
        searchRequest.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));

        //1.查询,获取查询结果
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        //7.获取Hits数据 数组
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            Goods goods = JSON.parseObject(hit.getSourceAsString(), Goods.class);
            System.out.println(goods);
        }
    }

16、模糊查询

/**
     * 模糊查询
     */
    @Test
    public void wildCardQuery() throws Exception{
        SearchRequest searchRequest = new SearchRequest("student");

        searchRequest.source(new SearchSourceBuilder().query(QueryBuilders.wildcardQuery("name","*x*")));

        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            Student student = JSON.parseObject(hit.getSourceAsString(), Student.class);
            System.out.println(student);
        }
    }

17、范围查询

 /**
     * 范围查询
     */
    @Test
    public void rangeQuery() throws Exception{
        SearchRequest searchRequest = new SearchRequest("student");
        searchRequest.source(new SearchSourceBuilder().query(QueryBuilders.rangeQuery("age").gte(0).lte(20)));
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            Student student = JSON.parseObject(hit.getSourceAsString(), Student.class);
            System.out.println(student);
        }
    }

18、queryString

 /**
     * queryString
     */
    @Test
    public void queryString() throws Exception{
        SearchRequest searchRequest = new SearchRequest("goods");
        searchRequest.source(new SearchSourceBuilder().query(QueryBuilders.queryStringQuery("华为手机").field("title").field("categoryName").field("brandName").defaultOperator(Operator.OR)));
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            Goods goods = JSON.parseObject(hit.getSourceAsString(), Goods.class);
            System.out.println(goods);
        }
    }

19、布尔查询

/**
     * 布尔查询
     */
    @Test
    public void boolQuery() throws Exception{
        SearchRequest searchRequest = new SearchRequest("goods");
        searchRequest.source(new SearchSourceBuilder()
                .query(QueryBuilders.boolQuery()
                        .filter(QueryBuilders.matchQuery("title","手机"))
                        .filter(QueryBuilders.rangeQuery("price").gte(1000).lte(2000))));
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            Goods goods = JSON.parseObject(hit.getSourceAsString(), Goods.class);
            System.out.println(goods);
        }
    }

20、聚合查询

    /**
     * 聚合查询
     */
    @Test
    public void aggQuery() throws Exception{
        SearchRequest searchRequest = new SearchRequest("student");
        searchRequest.source(new SearchSourceBuilder()
                .aggregation(AggregationBuilders
                        .terms("hello_world")
                        .field("age").size(2)
                        ));
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        for (SearchHit hit : search.getHits().getHits()) {
            Student student = JSON.parseObject(hit.getSourceAsString(), Student.class);
            System.out.println(student);
        }
    }

21、高亮查询

 /**
     * 高亮查询
     * 1. 设置高亮
     *      * 高亮字段
     *      * 前缀
     *      * 后缀
     * 2. 将高亮了的字段数据,替换原有数据
     */
    @Test
    public void highLightQuery() throws Exception{
        SearchRequest searchRequest = new SearchRequest("student");
        searchRequest.source(new SearchSourceBuilder()
                .query(QueryBuilders.matchQuery("address","江西"))//设置高亮字段
                .highlighter(new HighlightBuilder()
                        .field("address")//高亮字段
                        .preTags("<font color='red'>")//前缀
                        .postTags("</font>")));//后缀
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        for (SearchHit hit : search.getHits().getHits()) {
            Student student = JSON.parseObject(hit.getSourceAsString(), Student.class);

            //获取高亮结果,替换student中的address
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField address = highlightFields.get("address");
            Text[] fragments = address.fragments();
            //替换
            student.setAddress(fragments[0].toString());
            System.out.println(student);
        }
    }

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1075929.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

C++对string进行大小写转换的三种方法

C对string进行大小写转换的三种方法 方法一&#xff1a;下标 #include <iostream> #include <string> using namespace std;int main() {string s "ABCDEFG";for( int i 0; i < s.size(); i ){s[i] tolower(s[i]);}cout<<s<<endl;re…

详细解说iptables 高阶用法,用来完成哪些高效率网络路由策略场景,iptables 实现域名过滤,Linux如何利用iptables屏蔽某些域名?

详细解说iptables 高阶用法,用来完成哪些高效率网络路由策略场景,iptables 实现域名过滤,Linux如何利用iptables屏蔽某些域名? Linux利用iptables屏蔽某些域名 以下规则是屏蔽以 youtube.com 为主的所有一级 二级 三级等域名。 iptables -A OUTPUT -m string --string &qu…

XLSX.utils.sheet_to_json()解析excel,给空的单元格赋值为空字符串

前言 今天用到XLSX来解析excel文件&#xff0c;调用XLSX.utils.sheet_to_json(worksheet)&#xff0c;发现如果单元格为空的话&#xff0c;解析出来的结果&#xff0c;就会缺少相应的key&#xff08;如图所示&#xff09;。但是我想要单元格为空的话&#xff0c;值就默认给空字…

layui tree监控选中事件,同步选中和取消

需求&#xff1a;需要分配权限时&#xff0c;要通过组织架构分配&#xff0c;也要通过角色分配&#xff0c;还是把选择的结果显示出来 结果如下图 代码分页面&#xff0c;类和SQL 页面&#xff1a; <% Page Language"C#" AutoEventWireup"true" Code…

ElasticSearch搜索引擎: 内存分析与设置

在 Elasticsearch 的运行过程中&#xff0c;如何合理分配与设置内存是一件十分重要的事情&#xff0c;否则十分容易出现各种问题。 一、Elasticsearch为什么吃内存&#xff1a; 我们先看下 ES 服务器的总体内存消耗情况&#xff1a; 对于Query Cache、Request Cache、Field…

IT和OT 之间的教育鸿沟

自动化行业正在大力倡导开放自动化系统&#xff0c;使更多IT技术能够导入传统的自动控制行业。并且提出让开放自动化系统消除IT和OT 之间的鸿沟。笔者看来&#xff0c;IT和OT 之间除了技术上的鸿沟之外&#xff0c;还存在着人才鸿沟。近年来&#xff0c;面向智能制造行业的软件…

生物制药公司【Lexeo Therapeutics】申请1亿美元纳斯达克IPO上市

来源&#xff1a;猛兽财经 作者&#xff1a;猛兽财经 猛兽财经获悉&#xff0c;生物制药公司【Lexeo Therapeutics】近期已向美国证券交易委员会&#xff08;SEC&#xff09;提交招股书&#xff0c;申请在纳斯达克IPO上市&#xff0c;股票代码为(LXEO),Lexeo Therapeutics计划…

万万没想到有一天居然可以在 Mac 上玩游戏,而且还是原神!

万万没想到有一天居然可以在 Mac 上玩游戏&#xff0c;而且还是原神&#xff0c;我真的哭死~ 是这样的&#xff0c;我以前一直用 Mac 来办公也没想过要打游戏&#xff0c;在我心中 Mac 就是用来办公的&#xff0c;生产力工具&#xff0c;直到有一天我刷到一个视频&#xff0c;…

开发餐饮类私域流量是开发应用APP还是小程序还是低代码跨平台APP分析他的利与弊

在开发餐饮类应用程序时&#xff0c;我们需要先了解市场需求&#xff0c;定义目标受众&#xff0c;并提供独特的功能。个人感觉我们提供周围的在线订购、外卖服务、用户评价等功能&#xff0c;以吸引用户。同时&#xff0c;设计用户习惯的界面&#xff0c;使用户轻松选择自己的…

Qt绘图系统

文章目录 一.Qt绘图系统简介二.支持绘图系统的类三.绘图后端四.绘图和填充绘图填充Qt::BrushStyle 五.坐标系系统 一.Qt绘图系统简介 Qt的绘画系统支持使用相同的API在屏幕和打印设备上进行绘画&#xff0c;并且主要基于QPainter、QPaintDevice和QPaintEngine类。这种方法的主…

充电100%并非都是美事,有时少点更有溢出!如何正确为iPhone充电

iPhone是非凡的设备&#xff0c;但一旦电池耗尽&#xff0c;它们就会失去光泽。这就是为什么照看电池内部并确保始终正确充电很重要。 在这篇文章中&#xff0c;我们解释了如果你想让你的iPhone每天运行到深夜&#xff0c;并尽可能多地保持这种状态&#xff0c;你需要采取的步…

灰豚数字人平台AI创作助手,一键成片简化短视频制作过程,创作量突破百万!

国内AI语言大模型越来越多&#xff0c;人工智能已经全面进入我们的日常生活。其中&#xff0c;灰豚AI数字人平台的AI一键成片技术以其特独优势必&#xff0c;越来越受到短视频创作的青睐。本文将详细介绍灰豚AI数字人平台的应用场景以未来的发展前景。 灰豚数字人官网 一、灰豚…

Vue中使用Echarts封装为公用组件(简单复制粘贴)

Vue中封装Echarts组件 前提直奔主题 本文以Vue3代码演示 Vue2同理 前提 中文官网&#xff1a; https://echarts.apache.org/zh/index.html npm安装Echarts npm install echarts or pnpm install echarts or yarn add echarts直奔主题 创建Echarts.vue文件&#xff0c;代码如…

【Java每日一题】— —第二十六题:编程定义一个经理类Manager。(2023.10.10)

&#x1f383;个人专栏&#xff1a; &#x1f42c; 算法设计与分析&#xff1a;算法设计与分析_IT闫的博客-CSDN博客 &#x1f433;Java基础&#xff1a;Java基础_IT闫的博客-CSDN博客 &#x1f40b;c语言&#xff1a;c语言_IT闫的博客-CSDN博客 &#x1f41f;MySQL&#xff1a…

【Java】Java中的零拷贝

物理内存 计算机物理内存条的容量&#xff0c;比如我们买电脑会关注内存大小有多少G&#xff0c;这个容量就是计算机的物理内存。 虚拟内存 操作系统为每个进程分配了独立的虚拟地址空间&#xff0c;也就是虚拟内存&#xff0c;虚拟地址空间又分为用户空间和内核空间&#x…

[网鼎杯 2018]Comment git泄露 / 恢复 二次注入 bash_history文件查看

首先我们看到账号密码有提示了 我们bp爆破一下 我首先对数字爆破 因为全字符的话太多了 爆出来了哦 所以账号密码也出来了 zhangwei zhangwei666 没有什么用啊 扫一下吧 有git git泄露 那泄露看看 真有 <?php include "mysql.php"; session_start(); if(…

JUC第二十一讲:JUC线程池:ScheduledThreadPoolExecutor详解

JUC线程池&#xff1a;ScheduledThreadPoolExecutor详解 本文是JUC第二十一讲&#xff0c;JUC线程池: ScheduledThreadPoolExecutor详解。在很多业务场景中&#xff0c;我们可能需要周期性的运行某项任务来获取结果&#xff0c;比如周期数据统计&#xff0c;定时发送数据等。在…

07_项目开发_用户信息列表

1 用户信息列表内容展示 用户信息列表&#xff0c;主要完成用户信息的添加、删除、修改和查找功能。 用户列表页面效果&#xff1a; 单击“添加用户”按钮&#xff0c;进入添加用户页面。 填写正确的信息后&#xff0c;单击“添加用户”按钮&#xff0c;会直接跳转到用户列表…

算法题:买卖股票的最佳时机 II (贪心算法解决股票问题)

这道题是贪心算法的中级难度练习题&#xff0c;由于题目设定&#xff0c;整个价格都是透明的&#xff0c;这里并不涉及需要预测股票涨势的问题。解决思路不难&#xff0c;就是一旦股票价格开始下降了就买入&#xff0c;一旦上升了&#xff0c;就赶紧卖出。&#xff08;完整题目…

算法题:盛最多水的容器(贪心算法双指针问题)

这个题目乍一看就是双指针&#xff0c;没想到官方解答也是双指针&#xff0c;我在官方的基础上优化了一下下&#xff0c;左右两边各一个指针&#xff0c;每次移动短的那一头的时候&#xff0c;不是移动一格&#xff0c;而是找到比短的那一头要长一点的&#xff0c;再进行比较。…