分布式搜索引擎--Elasticsearch

news2024/9/20 22:54:25

1.1 相关术语

  1. 和mysql类比
    索引:数据库,database,6.0以后变化,对应表
    类型:table,6.0以后变化,废弃
    文档:一张表里的一行
    字段:一个属性就是一个字段

  2. 和分布式相关
    集群:分布式部署
    节点:每一台服务器
    分片:对索引进一步的划分
    副本:对分片的备份

1.2 安装中文分词插件

上 github下载Elasticsearch ik

1.3 通过命令行访问Elasticsearch服务器

  1. 访问集群健康状况curl -X GET "localhost:9200/_cat/health?v"
    在这里插入图片描述
    timestamp:时间
    cluster:集群
    status:状态,green健康
    node.total:节点数
    node.data:
    shards:
    pri:
    relo:
    init:
    unassign:
    pending_tasks:
    max_task_wait_time:
    active_shards_percent:

  2. 查看节点curl -X GET "localhost:9200/_cat/nodes?v"
    ip:127.0.0.1,表示本机
    heap.percent:堆内存占用量
    ram.percent:内存占用量
    cpu:cpu占用量

  3. 查看当前服务器多少个索引curl -X GET "localhost:9200/_cat/indices?v",当前没有索引
    在这里插入图片描述

  4. 创建索引curl -X PUT "localhost:9200/test",返回结果是json格式
    在这里插入图片描述

  5. 再次查看后可以查到一个索引curl -X GET "localhost:9200/_cat/indices?v",健康状况yellow,因为没有指定分片和副本,没有备份,能用但是有风险
    在这里插入图片描述

  6. 删除索引curl -X DELETE "localhost:9200/test"
    在这里插入图片描述

2. Spring整合Elasticsearch

在这里插入图片描述

.1 引入依赖

  1. pom.xml
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

2.2 配置Elasticsearch

2.2.1 application.properties

① 集群名字
② 节点。9200是http端口,9300是tcp端口

# ElasticsearchProperties
spring.data.elasticsearch.cluster-name=nowcoder
spring.data.elasticsearch.cluster-nodes=127.0.0.1:9300

2.2.2 CommunityApplication

redis 和 es 底层都基于 netty。二者有冲突,在CommunityApplication类中配置

@PostConstruct
public void init() {
    // 解决netty启动冲突问题
    // see Netty4Utils.setAvailableProcessors()
    System.setProperty("es.set.netty.runtime.available.processors", "false");
}

2.3 Spring整合Elasticsearch

2.3.1 DiscussPost

  1. 在实体类DiscussPost上增加注解
  2. 属性上增加注解
  3. 主要是 title 和 content
  4. analyzer = "ik_max_word":存储策略,尽量把这句话拆分成尽量多的单词,增加搜索范围
  5. "ik_smart":搜索策略,聪明分词器
@Document(indexName = "discusspost", type = "_doc", shards = 6, replicas = 3)
public class DiscussPost {
	@Id
    private int id;

    @Field(type = FieldType.Integer)
    private int userId;

    // 互联网校招
    @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
    private String title;

    @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
    private String content;

    @Field(type = FieldType.Integer)
    private int type;

    @Field(type = FieldType.Integer)
    private int status;

    @Field(type = FieldType.Date)
    private Date createTime;

    @Field(type = FieldType.Integer)
    private int commentCount;

    @Field(type = FieldType.Double)
    private double score;
	
	……
}

2.3.2 DiscussPostRepository

在dao下新建elasticsearch,实现DiscussPostRepository,继承时声明泛型,主键类型

 

package com.nowcoder.community.dao.elasticsearch;

import com.nowcoder.community.entity.DiscussPost;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface DiscussPostRepository extends ElasticsearchRepository<DiscussPost, Integer> {

}

2.3.3 ElasticsearchTests

  • 插入命令
@Test
public void testInsert() {
    discussRepository.save(discussMapper.selectDiscussPostById(241));
    discussRepository.save(discussMapper.selectDiscussPostById(242));
    discussRepository.save(discussMapper.selectDiscussPostById(243));
}
  • 批量插入
@Test
public void testInsertList() {
    discussRepository.saveAll(discussMapper.selectDiscussPosts(101, 0, 100));
    discussRepository.saveAll(discussMapper.selectDiscussPosts(102, 0, 100));
    discussRepository.saveAll(discussMapper.selectDiscussPosts(103, 0, 100));
    discussRepository.saveAll(discussMapper.selectDiscussPosts(111, 0, 100));
    discussRepository.saveAll(discussMapper.selectDiscussPosts(112, 0, 100));
    discussRepository.saveAll(discussMapper.selectDiscussPosts(131, 0, 100));
    discussRepository.saveAll(discussMapper.selectDiscussPosts(132, 0, 100));
    discussRepository.saveAll(discussMapper.selectDiscussPosts(133, 0, 100));
    discussRepository.saveAll(discussMapper.selectDiscussPosts(134, 0, 100));
}
  • 更新数据
@Test
public void testUpdate() {
    DiscussPost post = discussMapper.selectDiscussPostById(231);
    post.setContent("我是新人,使劲灌水.");
    discussRepository.save(post);
}
  • 删除所有数据
@Test
public void testDelete() {
    // discussRepository.deleteById(231);
    discussRepository.deleteAll();
}

2.3.4 ElasticsearchTests.testSearchByRepository()

  1. 构造查询条件:SearchQuery
  2. 搜索条件构造:QueryBuilders
  3. 排序条件构造:SortBuilders
  4. 分页查询条件:PageRequest
  5. 高亮条件:HighlightBuilder
  6. es会返回两份数据,一份原始数据,一份高亮显示数据
 @Test
public void testSearchByRepository() {
    SearchQuery searchQuery = new NativeSearchQueryBuilder()
            .withQuery(QueryBuilders.multiMatchQuery("互联网寒冬", "title", "content"))
            .withSort(SortBuilders.fieldSort("type").order(SortOrder.DESC))
            .withSort(SortBuilders.fieldSort("score").order(SortOrder.DESC))
            .withSort(SortBuilders.fieldSort("createTime").order(SortOrder.DESC))
            .withPageable(PageRequest.of(0, 10))
            .withHighlightFields(
                    new HighlightBuilder.Field("title").preTags("<em>").postTags("</em>"),
                    new HighlightBuilder.Field("content").preTags("<em>").postTags("</em>")
            ).build();

    // elasticTemplate.queryForPage(searchQuery, class, SearchResultMapper)
    // 底层获取得到了高亮显示的值, 但是没有返回.

    Page<DiscussPost> page = discussRepository.search(searchQuery);
    System.out.println(page.getTotalElements());
    System.out.println(page.getTotalPages());
    System.out.println(page.getNumber());
    System.out.println(page.getSize());
    for (DiscussPost post : page) {
        System.out.println(post);
    }
}

2.3.5 ElasticsearchTests.testSearchByTemplate()

@Test
public void testSearchByTemplate() {
    SearchQuery searchQuery = new NativeSearchQueryBuilder()
            .withQuery(QueryBuilders.multiMatchQuery("互联网寒冬", "title", "content"))
            .withSort(SortBuilders.fieldSort("type").order(SortOrder.DESC))
            .withSort(SortBuilders.fieldSort("score").order(SortOrder.DESC))
            .withSort(SortBuilders.fieldSort("createTime").order(SortOrder.DESC))
            .withPageable(PageRequest.of(0, 10))
            .withHighlightFields(
                    new HighlightBuilder.Field("title").preTags("<em>").postTags("</em>"),
                    new HighlightBuilder.Field("content").preTags("<em>").postTags("</em>")
            ).build();

    Page<DiscussPost> page = elasticTemplate.queryForPage(searchQuery, DiscussPost.class, new SearchResultMapper() {
        @Override
        public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> aClass, Pageable pageable) {
            SearchHits hits = response.getHits();
            if (hits.getTotalHits() <= 0) {
                return null;
            }

            List<DiscussPost> list = new ArrayList<>();
            for (SearchHit hit : hits) {
                DiscussPost post = new DiscussPost();

                String id = hit.getSourceAsMap().get("id").toString();
                post.setId(Integer.valueOf(id));

                String userId = hit.getSourceAsMap().get("userId").toString();
                post.setUserId(Integer.valueOf(userId));

                String title = hit.getSourceAsMap().get("title").toString();
                post.setTitle(title);

                String content = hit.getSourceAsMap().get("content").toString();
                post.setContent(content);

                String status = hit.getSourceAsMap().get("status").toString();
                post.setStatus(Integer.valueOf(status));

                String createTime = hit.getSourceAsMap().get("createTime").toString();
                post.setCreateTime(new Date(Long.valueOf(createTime)));

                String commentCount = hit.getSourceAsMap().get("commentCount").toString();
                post.setCommentCount(Integer.valueOf(commentCount));

                // 处理高亮显示的结果
                HighlightField titleField = hit.getHighlightFields().get("title");
                if (titleField != null) {
                    post.setTitle(titleField.getFragments()[0].toString());
                }

                HighlightField contentField = hit.getHighlightFields().get("content");
                if (contentField != null) {
                    post.setContent(contentField.getFragments()[0].toString());
                }

                list.add(post);
            }

            return new AggregatedPageImpl(list, pageable,
                    hits.getTotalHits(), response.getAggregations(), response.getScrollId(), hits.getMaxScore());
        }
    });

    System.out.println(page.getTotalElements());
    System.out.println(page.getTotalPages());
    System.out.println(page.getNumber());
    System.out.println(page.getSize());
    for (DiscussPost post : page) {
        System.out.println(post);
    }
}

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

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

相关文章

NLP学习笔记(六) Transformer简明介绍

大家好&#xff0c;我是半虹&#xff0c;这篇文章来讲 Transformer\text{Transformer}Transformer&#xff0c;想要获取更多相关文章&#xff0c;欢迎关注 自然语言处理 专栏 在之前的两篇文章中&#xff0c;我们介绍过序列到序列模型以及注意力机制在序列到序列模型中的应用 …

Linux开启Docker远程访问并设置安全访问(证书密钥),附一份小白一键设置脚本哦!

前言 喜欢折腾慢慢看&#xff0c;不喜欢折腾直接跳到小简下文的一键脚本那里&#xff0c;两分钟搞好。 我的博客&#xff1a;https://blog.ideaopen.cn 我的公众号&#xff1a;小简聊开发 开启远程访问 编辑docker.service文件 vi /usr/lib/systemd/system/docker.service # …

Python FastAPI 框架 操作Mysql数据库 增删改查

2 比 1 更容易理解&#xff0c;可以先看2&#xff08;单文件级别&#xff09; 1、FastAPI 框架 操作Mysql数据库(项目多文件级别) FastAPI 可以使用任何您想要的关系型数据库。 在这里&#xff0c;让我们看一个使用着SQLAlchemy的示例。 您可以很容易地将SQLAlchemy支持任何…

每天进步一点点,今天来学结构体

什么是结构体&#xff1f; C 语言允许用户自己指定这样一种数据结构&#xff0c;它由不同类型的数据组合成一个整体&#xff0c;以便引用&#xff0c;这些组合在一个整体中的数据是互相联系的&#xff0c;这样的数据结构称为结构体&#xff0c;它相当于其它高级语言中记录。 …

01、数据结构——数组

一、数据结构与算法 数据结构是一门研究组织数据方式的学科&#xff0c;有了编程语言也就有了数据结构。学好数据结构可以编写出更加漂亮、更加有效率的代码。程序数据结构算法数据结构是算法的基础 二、稀疏数组&#xff1a; 1、基本介绍&#xff1a; 当一个数组中大部分元…

【Javascript】文本转语音SpeechSynthesisUtterance

SpeechSynthesisUtterance基本介绍 SpeechSynthesisUtterance是HTML5中新增的API,用于将指定文字合成为对应的语音.也包含一些配置项,指定如何去阅读(语言,音量,音调)等 SpeechSynthesisUtterance基本属性 SpeechSynthesisUtterance.lang 获取并设置话语的语言 SpeechSynthesis…

InfluxDB 笔记

概念 Measurement 类似于表名。 A measurement acts as a container for tags, fields, and timestamps. Tag 补充描述数据的信息&#xff0c;如示例中的location和scientist描述了该数据的采集地和采集人。这两个称为Tag Key&#xff0c;具体的值则称为Tag Value&#xff0c…

小程序基础篇-视图与逻辑

本次学习目标&#xff1a;实现页面间的导航跳转实现下拉刷新实现上拉加载更多知道小程序常用的生命周期函数1.页面导航页面导航指的是页面之前相互的跳转浏览器之间的页面导航有两种&#xff1a;<a>;location.href小程序之间的页面导航有两种&#xff1a;声明式导航&…

告警与恢复告警原理及实现

一、 背景自“双碳”政策提出以来&#xff0c;KaiwuDB 聚焦“数字能源”领域&#xff0c;为用户打造数字能源管理平台&#xff0c;旨在提升综合能源和碳资产管理能力。数字能源管理平台是以 KaiwuDB 为核心建设的云-边-端一体化数据服务平台&#xff0c;致力于为 IoT、工业互联…

前言技术--swagger

目录一、前后端分离的特点二、在没有swagger之前三、swagger的作用四、swagger的优点五、集成swagger5.1 新建springboot项目5.2 集成swagger5.3 开发一个controller用于测试5.4 启动服务&#xff0c;验证集成效果六、swagger常用注解七、swagger使用综合案例一、前后端分离的特…

Python的PyQt框架的使用-常用控件篇

Python的PyQt框架的使用-常用控件篇一、前言二 、QLineEdit 文本框三 、QPushButton按钮控件四、QRadioButton 单选按钮一、前言 个人主页: ζ小菜鸡大家好我是ζ小菜鸡&#xff0c;小伙伴们&#xff0c;让我们一起来学习Python的PyQt框架的常用控件。如果文章对你有帮助、欢迎…

第一个程序——构建一个ServerUI

简介 本次程序设计均使用python实现&#xff0c;使用sql server对聊天室用户的数据进行存储。通过python socket套接字编程&#xff0c;实现了在线聊天室的功能&#xff0c;并使用python tkinter进行UI界面的设计。 思路 由计算机网络的基础知识易知&#xff0c;两个主机之间…

基于LSTMGRU的微博突发事件分析与谣言检测(附完整的代码+报告)

问题描述及方法基础 本章主要对课题研究所涉及的机器学习、自然语言处理的原理和方法进行介绍,主要分为四部分,第一部分是将本课谣言检测任务的符号化描述;第二部分是微博数据的预处理,包括语言模型、文本分词等技术;第三部分与第四部分分别是本文搭建的微博谣言检测模型所…

py字符串的格式化笔记

print():和cjava差不多&#xff0c;只是逗号变了&#xff0c;其中 %s 就是模板中的占位符&#xff0c;表示这个位置先占着&#xff0c;待会儿要有数据填入到这里。然后再提供一个元组&#xff0c;里面依次存放需要填入到 %s 位置 的数据。这里是使用变量 (salary,tax,aftertax)…

CSS.前端基础.html

什么是 CSS? CSS 指层叠样式表 (Cascading Style Sheets)样式定义如何显示 HTML 元素样式通常存储在样式表中把样式添加到 HTML 4.0 中&#xff0c;是为了解决内容与表现分离的问题外部样式表可以极大提高工作效率外部样式表通常存储在 CSS 文件中多个样式定义可层叠为一个示…

丝绸之路也可以是科技传播之路

唐宋元海外贸易 618年-1368年 王孝通 生卒年代不详 孙思邈541年—682年 一行 公元683年-公元727年 李淳风 602年&#xff0d;670年 沈括 1031年&#xff0d;1095年 郭守敬 1231年&#xff0d;1316年 扎马鲁丁生卒年代不详 阿拉伯帝国 632年-1258年 阿尔花拉子模 780年&#xf…

【深度强化学习】【论文阅读】【双臂模仿】Deep Imitation Learning for BimanualRobotic Manipulation

title: Deep Imitation Learning for BimanualRobotic Manipulation date: 2023-01-15T20:54:56Z lastmod: 2023-01-19T18:31:57Z Deep Imitation Learning for BimanualRobotic Manipulation 1 Introduction 文中使用的模型是一个深度的、分层的、模块化的架构。与 baselin…

微服务负载均衡器Ribbon学习笔记

目录 1.什么是Ribbon 1.1 客户端的负载均衡 1.2 服务端的负载均衡 1.3 常见负载均衡算法 2. Nacos使用Ribbon 3. Ribbon负载均衡策略 4.修改默认负载均衡策略 方式1&#xff1a;通过自定义配置类来实现 方式2&#xff1a;通过修改配置文件实现&#xff08;推荐&#xf…

9、jQuery

jQuery库&#xff1a;里面存在大量的JavaScript函数 官网&#xff1a;https://jquery.com/ 9.1 获取jQuery jQuery引入 cdn 引入 <script src"https://cdn.bootcss.com/jquery/3.4.1/core.js"></script>本地引入 <script src"lib/jquery-3.6.3.…

C语言练习——3

C语言练习——3一、 操作符练习1.1交换两个变量&#xff08;不创建临时变量&#xff09;1.2 打印整数二进制的奇数位和偶数位1.3[二进制中1的个数](https://www.nowcoder.com/questionTerminal/8ee967e43c2c4ec193b040ea7fbb10b8)1.4[两个整数二进制位不同个数](https://www.no…