javaAPI操作Elasticsearch

mapping属性


mapping是对索引库中文档的约束, 常见的mapping属性包括:

  • type: 字段数据类型,常见的简单类型有:
    • 字符串: text(可分词的文本), keyword(精确值, 例如: 品牌,国家)
    • 数值: long, integer, short, byte, double, float
    • 布尔: boolean
    • 日期: date
    • 对象: object
  • index: 是否创建索引, 默认为true
  • analyzer: 使用哪种分词器
  • properties: 该字段的子字段

索引库操作


创建索引库

PUT /zyw
{
  "mappings": {
    "properties": {
      "info": {
        "type": "text",
        "analyzer": "ik_smart"
      },
      "email": {
        "type": "keyword",
        "index": false
      },
      "name": {
        "type": "object",
        "properties": {
          "firstName": {
            "type": "keyword"
          },
          "lastName":{
            "type":"keyword"
          }
        }
      }
    }
  }
}

查看索引库

GET /zyw

删除索引库

DELETE /zyw

修改索引库, 添加新字段

索引库和mapping一旦创建无法修改, 但是可以添加新字段

PUT /zyw/_mapping
{
  "properties": {
    "age": {
      "type": "integer"
    }
  }
}

文档操作


新增文档

POST /zyw/_doc/1
{
  "info": "java是最好的语言",
  "email": "zy@163.com",
  "name": {
    "firstName": "云",
    "lastName": "赵"
  }
}

查询文档

GET /zyw/_doc/1

删除文档

DELETE /zyw/_doc/1

修改文档

  • 全量修改, 会删除旧文档, 添加新文档
PUT /zyw/_doc/1
{
  "info": "java是最好的语言",
  "email": "zy@163.com",
  "name": {
    "firstName": "云",
    "lastName": "赵"
  }
}
  • 局部修改
POST /zyw/_update/1
{
  "doc": {
    "email": "test@163.com"
  }
}

RestClient操作索引库


在这里插入图片描述

  • 引入依赖
		<dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.12.1</version>
        </dependency>

注意:
在这里插入图片描述
springboot管理了elasticsearch的部分依赖, 查看springboot的依赖管理
在这里插入图片描述
我们需要在pom文件中定义这个版本值,覆盖springboot的
在这里插入图片描述

  • HotelDoc.java
@Data
@NoArgsConstructor
public class HotelDoc {
    private Long id;
    private String name;
    private String address;
    private Integer price;
    private Integer score;
    private String brand;
    private String city;
    private String starName;
    private String business;
    private String location;
    private String pic;

    public HotelDoc(Hotel hotel) {
        this.id = hotel.getId();
        this.name = hotel.getName();
        this.address = hotel.getAddress();
        this.price = hotel.getPrice();
        this.score = hotel.getScore();
        this.brand = hotel.getBrand();
        this.city = hotel.getCity();
        this.starName = hotel.getStarName();
        this.business = hotel.getBusiness();
        this.location = hotel.getLatitude() + ", " + hotel.getLongitude();
        this.pic = hotel.getPic();
    }
}
  • hotel索引库
{
  "mappings": {
    "properties": {
      "id": {
        "type": "keyword"
      },
      "name": {
        "type": "text",
        "analyzer": "ik_max_word",
        "copy_to": "all"
      },
      "address": {
        "type": "keyword",
        "index": false
      },
      "price": {
        "type": "integer"
      },
      "score": {
        "type": "integer"
      },
      "brand": {
        "type": "keyword",
        "copy_to": "all"
      },
      "city": {
        "type": "keyword"
      },
      "starName": {
        "type": "keyword"
      },
      "business": {
        "type": "keyword",
        "copy_to": "all"
      },
      "location": {
        "type": "geo_point"
      },
      "pic": {
        "type": "keyword",
        "index": false
      },
      "all": {
        "type": "text",
        "analyzer": "ik_max_word"
      }
    }
  }
}

基于elasticsearch的规则, id用keyword

  • 操作索引库
import com.zyw.elasticsearchdemo.constants.HotelConstants;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.IOException;

public class ElasticsearchDemoApplicationTests {

    private RestHighLevelClient client;


    /**
     * 删除索引库
     */
    @Test
    void deleteHotelIndex() throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("hotel");
        client.indices().delete(request, RequestOptions.DEFAULT);
    }

    /**
     * 判断索引库是否存在
     */
    @Test
    void existHotelIndex() throws IOException {
        GetIndexRequest request = new GetIndexRequest("hotel");
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists ? "索引库已经存在" : "索引库不存在");
    }

    /**
     * 创建索引库
     */
    @Test
    void createHotelIndex() throws IOException {
        // 1.创建request对象
        CreateIndexRequest request = new CreateIndexRequest("hotel");
        // 2.准备请求的参数, DSL语句
        request.source(HotelConstants.MAPPING_TEMPLATE, XContentType.JSON);
        // 3. 发送请求
        client.indices().create(request, RequestOptions.DEFAULT);
    }

    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://82.114.174.50:9200")));
    }

    @AfterEach
    void tearDown() throws IOException {
        client.close();
    }
}

RestClient操作文档


import cn.hutool.json.JSONUtil;
import com.zyw.elasticsearchdemo.mapper.HotelMapper;
import com.zyw.elasticsearchdemo.pojo.Hotel;
import com.zyw.elasticsearchdemo.pojo.HotelDoc;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.List;

@SpringBootTest
public class ElasticsearchDemoApplicationTests1 {

    private RestHighLevelClient client;

    @Autowired
    private HotelMapper hotelMapper;


    /**
     * 删除文档
     */
    @Test
    void deleteDocument() throws IOException {
        DeleteRequest request = new DeleteRequest("hotel", "200216665");
        client.delete(request, RequestOptions.DEFAULT);

    }

    /**
     * 修改文档-局部更新, 全量和创建一样
     */
    @Test
    void updateDocument() throws IOException {
        UpdateRequest request = new UpdateRequest("hotel", "200216665");
        request.doc("price", 2600, "starName", "六钻");
        client.update(request, RequestOptions.DEFAULT);
    }

    /**
     * 查询文档
     */
    @Test
    void getDocument() throws IOException {
        // 准备request对象
        GetRequest request = new GetRequest("hotel", "200216665");
        // 发送请求
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        String json = response.getSourceAsString();
        HotelDoc hotelDoc = JSONUtil.toBean(json, HotelDoc.class);
        System.out.println(hotelDoc);
    }

    /**
     * 新增文档
     */
    @Test
    void addDocument() throws IOException {
        // 根据id查询酒店数据
        Hotel hotel = hotelMapper.selectById(200216665);
        // 转换为文档对象
        HotelDoc hotelDoc = new HotelDoc(hotel);
        // 准备request对象
        IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
        // 准备json文档
        request.source(JSONUtil.toJsonStr(hotelDoc), XContentType.JSON);
        // 发送请求
        client.index(request, RequestOptions.DEFAULT);
    }

    /**
     * 批量导入文档
     */
    @Test
    void batchAddDocument() throws IOException {
        List<Hotel> hotels = hotelMapper.selectList(null);
        BulkRequest request = new BulkRequest();
        for (Hotel hotel : hotels) {
            HotelDoc hotelDoc = new HotelDoc(hotel);
            request.add(new IndexRequest("hotel").id(hotelDoc.getId().toString())
                    .source(JSONUtil.toJsonStr(hotelDoc), XContentType.JSON));
        }
        // 发送
        client.bulk(request, RequestOptions.DEFAULT);
    }

    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://82.114.174.50:9200")));
    }

    @AfterEach
    void tearDown() throws IOException {
        client.close();
    }
}

DSL查询语法


分类和基本语法

在这里插入图片描述
在这里插入图片描述

全文检索查询

全文检索查询, 会对用户输入内容分词, 常用于搜索框搜索
在这里插入图片描述
在这里插入图片描述
建议把多个字段copy到一个字段里

精确查询

在这里插入图片描述
在这里插入图片描述

地理查询

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

复合查询

  • 复合(compound)查询: 复合查询可以将其他简单查询组合起来, 实现更复杂的搜索逻辑.
    • function score: 复分函数查询, 可以控制文档相关性算分, 控制文档排名. 例如百度竞价

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

搜索结果处理


排序

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

分页

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

高亮

在这里插入图片描述
在这里插入图片描述
默认字段要一致, 可以用require_field_match 取消一致

RestClient查询文档–高级查询


在这里插入图片描述
在这里插入图片描述

import cn.hutool.json.JSONUtil;
import com.zyw.elasticsearchdemo.pojo.HotelDoc;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.util.Map;

public class QueryDocumentTest {

    private RestHighLevelClient client;

    /**
     * 高亮
     */
    @Test
    void testHighlight() throws IOException {
        SearchRequest request = new SearchRequest("hotel");
        request.source().query(QueryBuilders.matchQuery("all", "维也纳"));
        // 高亮设置
        request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        handleResponse(response);
    }

    /**
     * 排序和分页
     */
    @Test
    void sortAndPage() throws IOException {
        SearchRequest request = new SearchRequest("hotel");
        request.source().sort("price", SortOrder.ASC).from(20).size(5);
        request.source().query(QueryBuilders.matchAllQuery());
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        handleResponse(response);
    }

    /**
     * bool查询
     * @throws IOException
     */
    @Test
    void testBool() throws IOException {
        SearchRequest request = new SearchRequest("hotel");
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 添加term
        boolQuery.must(QueryBuilders.termQuery("city", "上海"));
        // 添加range
        boolQuery.filter(QueryBuilders.rangeQuery("price").lte(500));
        request.source().query(boolQuery);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        handleResponse(response);
    }

    /**
     * match查询
     */
    @Test
    void testMatch() throws IOException {
        SearchRequest request = new SearchRequest("hotel");
        request.source().query(QueryBuilders.matchQuery("all", "如家"));
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        handleResponse(response);
    }

    /**
     * 处理结果
     * @param response
     */
    private static void handleResponse(SearchResponse response) {
        SearchHits searchHits = response.getHits();
        // 查询的总条数
        long total = searchHits.getTotalHits().value;
        System.out.println("total = " + total);
        // 查询的结果数组
        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : hits) {
            // 得到source
            String json = hit.getSourceAsString();
            HotelDoc hotelDoc = JSONUtil.toBean(json, HotelDoc.class);
            // 获取高亮结果
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            // 根据字段名获取高亮结果
            HighlightField highlightField = highlightFields.get("name");
            // 获取高亮值
            String name = highlightField.getFragments()[0].toString();
            // 覆盖非高亮结果
            hotelDoc.setName(name);
            System.out.println("hotelDoc = " + hotelDoc);
        }
    }


    /**
     * 查询所有
     * @throws IOException
     */
    @Test
    void testMatchAll() throws IOException {
        SearchRequest request = new SearchRequest("hotel");
        request.source().query(QueryBuilders.matchAllQuery());
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        handleResponse(response);
    }

    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://82.114.174.50:9200")));
    }

    @AfterEach
    void tearDown() throws IOException {
        client.close();
    }
}

补充


  • 分词
POST /_analyze
{
  "text": "java是最好的语言",
  "analyzer": "ik_smart"
}
  • 查所有
GET /hotel/_search

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

LLMs之Grok-1:Grok-1的简介、安装、使用方法之详细攻略

LLMs之Grok-1&#xff1a;Grok-1的简介、安装、使用方法之详细攻略 导读&#xff1a;马斯克旗下的xAI公司宣布开源名为Grok-1的混合专家模型&#xff0c;参数量达3140亿&#xff0c;为目前最大的开源大语言模型。xAI此举或将引领人工智能开源趋势&#xff0c;同时也将对不太Ope…

协议分类笔记

1.3 协议分类 通信的协议还是比较复杂的&#xff0c;java.net 包中包含的类和接口&#xff0c;它们提供低层次的通信细节。我们可以直接使用这些类和接口&#xff0c;来专注于网络程序开发&#xff0c;而不用考虑通信的细节。 java.net 包中提供了两种常见的网络协议的支持&a…

DevExpress WinForms crack,DevExpress WinForms组件套件和库

DevExpress WinForms crack,DevExpress WinForms组件套件和库 Reporting & Analytics - Reports, Pivot Tables, PDF Viewer. The DevExpress WinForms Subscription includes royalty-free user interface components for next-gen decision support systems. Whether you…

Java基础经典10道题

目录 for循环的嵌套 题目一: 求101到200之间的素数的个数,并打印 代码分析: 注意点: 题目二:开发验证码 代码分析: 题目三:数组元素的复制 代码分析: 题目四:评委打分 健壮版代码: 代码分析:看源码 注意点: 题目五:数字加密 优化版代码: 代码分析: 题目六:数字…

MeterSphere和Jmeter使用总结

一、MeterSphere 介绍 MeterSphere 是⼀站式开源持续测试平台&#xff0c;涵盖测试跟踪、接⼝测试、UI 测试和性能测试等&#xff0c;全 ⾯兼容 JMeter、Selenium 等主流开源标准&#xff0c;能够有效助⼒开发和测试团队在线共享协作&#xff0c;实现端到 端的测试管理跟踪…

2、RabbitMQ_安装

RabbitMQ安装文档 RabbitMQ官网下载地址&#xff1a;https://www.rabbitmq.com/download.html 1.安装依赖 在线安装依赖环境&#xff1a; yum install build-essential openssl openssl-devel unixODBC unixODBC-devel make gcc gcc-c kernel-devel m4 ncurses-devel tk tc x…

Java语言: 多线程

1. 线程调度 1.1 线程状态 线程是cpu任务调度的最小执行单位&#xff0c;每个线程拥有自己独立的程序计数器、虚拟机栈、本地方法栈。 线程状态&#xff1a;创建、就绪、运行、阻塞、死亡 1.2 线程状态切换 1.3 阻塞唤醒过程 阻塞&#xff1a; 这三个方法的调用都会使当前…

视频私有云,HDMI/AV多硬件设备终端接入,SFU/MCU视频会议交互方案。

在视频业务深入的过程中越来越多的硬件设备接入视频交互的视频会议中远程交互&#xff0c;有的是视频采集&#xff0c;有的是医疗影像等资料&#xff0c;都需要在终端承显&#xff0c;这就需要我们的设备终端能多设备&#xff0c;多协议接入&#xff0c;设备接入如下。 1&#…

2024年敏捷产品负责人CSPO认证培训

课程名称&#xff1a;Scrum Product Owner CSPO产品负责人认证 课程类型&#xff1a;经理级 课程简介&#xff1a; Scrum Product Owner产品负责人在Scrum产品开发当中扮演“舵手”的角色&#xff0c;他决定产品的愿景、路线图以及投资回报&#xff0c;他需要回答为什么做&am…

数据收集与分析

数据收集与分析是任何组织决策过程中的核心环节&#xff0c;特别是在确定关键性能指标&#xff08;KPIs&#xff09;、使用先进的数据分析工具和方法方面。以下是一个概述&#xff0c;旨在解释如何进行数据收集与分析&#xff0c;并确定KPIs。 1. 确定关键性能指标&#xff08…

windows DCMTK编译使用(qt) 医学图像

由于项目需要生成DICOM格式的图片&#xff0c;需要使用到第三方开源库DCMTK&#xff0c;于是研究了一番&#xff0c;该库是C编写的&#xff0c;DICOM主要用于医疗体系中&#xff0c;除了可以保存图片信息外&#xff0c;还可以储存患者信息&#xff0c;病例信息&#xff0c;医疗…

蓝桥杯刷题(十一)

1.卡片 反向思考&#xff0c;看k种卡片可以分给几位同学 代码 n int(input()) k 1 while k*(k1)<2*n:k1 print(k)2.美丽的2 代码 def f(x)->bool:while x:if x%102:return Truex//10return False cnt 0 for i in range(1,2021):if f(i):cnt1 print(cnt)3.单词分析 …

会话绑定实验

准备三台虚拟机 1. 安装epel镜像 2. 安装nginx 3. 配置nginx文件&#xff0c;启动服务 4. 管理剩余两台服务器 同时在剩余两台服务器里操作 5. 操作虚拟机二&#xff08;一&#xff09; 创建data文件夹&#xff0c;解压jdk到user/local下并进入&#xff0c;给jdk做个软链接 6. …

【详细解读】HTTP协议性能特征及性能测试方法

&#x1f604;作者简介&#xff1a; 小曾同学.com,一个致力于测试开发的博主⛽️&#xff0c;主要职责&#xff1a;测试开发、CI/CD 如果文章知识点有错误的地方&#xff0c;还请大家指正&#xff0c;让我们一起学习&#xff0c;一起进步。 &#x1f60a; 座右铭&#xff1a;不…

小程序云开发(十六):JavaScript基础

&#x1f517; 运行环境&#xff1a;小程序云开发 &#x1f6a9; 撰写作者&#xff1a;左手の明天 &#x1f947; 精选专栏&#xff1a;《python》 &#x1f525; 推荐专栏&#xff1a;《算法研究》 &#x1f510;#### 防伪水印——左手の明天 ####&#x1f510; &#x1f497…

Auto-DataProcessing:一组让制作数据集变轻松的脚本

前言 最近跟同学参加了个比赛&#xff0c;我负责Object-Detection的技术实现&#xff0c;需要从网上扒大量的数据(主办方每种识别物就给了一张demo&#x1f923;)&#xff0c;发现数据准备是一个真的是一个非常重要但又耗时耗力的过程。对我来说&#xff0c;给我一类待识别的标…

蓝桥杯-Sticks-DFS搜索

题目 样例输出是 6 5 题目中给错了&#xff0c;不知道什么时候会改。 思路 --剪枝&#xff0c;否则时间复杂度和空间复杂度过大&#xff0c;会超时。 --注意有多组测试样例时&#xff0c;需要将bool数组重新赋值为false。 --函数类型不是void&#xff0c;return语句不能省…

Selenium 自动化 —— Selenium IDE录制、回放、导出Java源码

Hello Selenium 示例 之前我们在专栏的第一篇文章中演示了使用使用Selenium进行百度搜索的Hello world示例。 代码不复杂非常简单&#xff1a; public static void main(String[] args) {WebDriver driver null;try {// 设置Chrome驱动的路径 // System.setPro…

UnityShader(十八) 透明度测试

上代码&#xff1a; Shader "Shader入门/透明度效果/AlphaTestShader" {Properties{_MainTex ("Texture", 2D) "white" {}_CutOff("CutOff",Range(0,1))1}SubShader{Tags { "Queue""AlphaTest" "IgnorePro…

SpringBoot中使用MybatisX插件的详细过程

MybatisX 是一款针对 MyBatis 框架的 IntelliJ IDEA 的快速开发插件&#xff0c;旨在提高 MyBatis 开发效率的工具。它提供了一系列功能来简化 MyBatis 的配置和使用&#xff0c;包括 XML 文件的智能补全、快速跳转、代码生成等功能。 实现细节 &#xff08;1&#xff09;在I…
最新文章