在nodejs中使用ElasticSearch(一)安装,使用

使用docker安装ElasticSearch和Kibana

1)创建相应的data文件夹和子文件夹用来持久化ElasticSearch和kibana数据

2)提前创建好elasticsearch配置文件 data/elasticsearch/config/elasticsearch.yml文件

# ======================== Elasticsearch Configuration =========================
#
# NOTE: Elasticsearch comes with reasonable defaults for most settings.
#       Before you set out to tweak and tune the configuration, make sure you
#       understand what are you trying to accomplish and the consequences.
#
# The primary way of configuring a node is via this file. This template lists
# the most important settings you may want to configure for a production cluster.
#
# Please consult the documentation for further information on configuration options:
# https://www.elastic.co/guide/en/elasticsearch/reference/index.html
#
xpack.security.enabled: false
network.host: 0.0.0.0
# xpack.security.enrollment.enabled: true

# xpack.security.http.ssl.enabled: true
# xpack.security.http.sslkeystore.path: certs/http.p12

# xpack.security.transport.ssl.enabled: true
# xpack.security.transport.ssl.verification_mode: certificate
# xpack.security.transport.ssl.client_authentication: required
# xpack.security.transport.ssl.keystore.path: elastic-certificates.p12
# xpack.security.transport.ssl.truststore.path: elastic-certificates.p12

# 禁用磁盘水位检查
cluster.routing.allocation.disk.watermark.low: 100%
cluster.routing.allocation.disk.watermark.high: 100%
cluster.routing.allocation.disk.watermark.flood_stage: 100%

# 禁用基于磁盘水位的磁盘卸载
cluster.routing.allocation.disk.threshold_enabled: false

# ---------------------------------- Cluster -----------------------------------
#
# Use a descriptive name for your cluster:
#
#cluster.name: my-application
#
# ------------------------------------ Node ------------------------------------
#
# Use a descriptive name for the node:
#
#node.name: node-1
#
# Add custom attributes to the node:
#
#node.attr.rack: r1
#
# ----------------------------------- Paths ------------------------------------
#
# Path to directory where to store the data (separate multiple locations by comma):
#
#path.data: /path/to/data
#
# Path to log files:
#
#path.logs: /path/to/logs
#
# ----------------------------------- Memory -----------------------------------
#
# Lock the memory on startup:
#
#bootstrap.memory_lock: true
#
# Make sure that the heap size is set to about half the memory available
# on the system and that the owner of the process is allowed to use this
# limit.
#
# Elasticsearch performs poorly when the system is swapping the memory.
#
# ---------------------------------- Network -----------------------------------
#
# By default Elasticsearch is only accessible on localhost. Set a different
# address here to expose this node on the network:
#
#network.host: 192.168.0.1
#
# By default Elasticsearch listens for HTTP traffic on the first free port it
# finds starting at 9200. Set a specific HTTP port here:
#
#http.port: 9200
#
# For more information, consult the network module documentation.
#
# --------------------------------- Discovery ----------------------------------
#
# Pass an initial list of hosts to perform discovery when this node is started:
# The default list of hosts is ["127.0.0.1", "[::1]"]
#
#discovery.seed_hosts: ["host1", "host2"]
#
# Bootstrap the cluster using an initial set of master-eligible nodes:
#
#cluster.initial_master_nodes: ["node-1", "node-2"]
#
# For more information, consult the discovery and cluster formation module documentation.
#
# ---------------------------------- Various -----------------------------------
#
# Allow wildcard deletion of indices:
#
#action.destructive_requires_name: false

3)提前创建好kibana配置文件 data/kibana/config/kibana.yml文件,配置为中文在kibana.yml中添加i18n.locale: "zh-CN" 参数

#
# ** THIS IS AN AUTO-GENERATED FILE **
#

# Default Kibana configuration for docker target
server.host: "0.0.0.0"
server.shutdownTimeout: "5s"
elasticsearch.hosts: [ "http://elasticsearch:9200" ]
monitoring.ui.container.elasticsearch.enabled: true
i18n.locale: "zh-CN" # 设置中文

4)创建docker-compose.yml文件,volumes下持久化数据保存到本机的路径可以自定义。

services:
  elasticsearch:
    image: elasticsearch:8.17.2
    container_name: elasticsearch
    environment:
      - ES_JAVA_OPTS=-Xms1g -Xmx1g
      - discovery.type=single-node
      - ELASTICSEARCH_PASSWORD=admin1234 # elastic 用户密码相同
    volumes:
      - D:/VScode/nodejs/intensify/docker/elasticsearch/data/elasticsearch/data:/usr/share/elasticsearch/data
      - D:/VScode/nodejs/intensify/docker/elasticsearch/data/elasticsearch/plugins:/usr/share/elasticsearch/plugins
      - D:/VScode/nodejs/intensify/docker/elasticsearch/data/elasticsearch/config/elasticsearch.yml:/usr/share/elasticsearch/config/elasticsearch.yml
    privileged: true
    networks:
      - elastic-net
    ports:
      - "9200:9200"
      - "9300:9300"

  kibana:
    image: kibana:8.17.2
    container_name: kibana
    environment:
      - ELASTICSEARCH_HOSTS=http://elasticsearch:9200
    volumes:
      - D:/VScode/nodejs/intensify/docker/elasticsearch/data/kibana/data:/usr/share/kibana/data
      - D:/VScode/nodejs/intensify/docker/elasticsearch/data/kibana/config/kibana.yml:/usr/share/kibana/config/kibana.yml
    networks:
      - elastic-net
    ports:
      - "5601:5601"

networks:
  elastic-net:
    driver: bridge

5)在docker-compose.yml所在位置运行下述命令,即可直接访问

docker compose up -d

​​​

分词插件安装

一、analysis-icu分词器 

analysis-icu 插件是基于 ICU(International Components for Unicode) 库的分词插件,主要用于处理 Unicode 字符串,支持多种语言的字符集和复杂的文本处理。ICU 是一个开源的跨平台库,支持国际化和本地化特性,尤其擅长处理多语言环境下的文本。

1)进入到运行的elasticSearch容器中 

docker exec -it containerID sh

 2)在ElasticSearch安装的根目录下,执行安装分词插件,安装完后重启

./bin/elasticsearch-plugin install analysis-icu

3)查看已安装的插件 

./bin/elasticsearch-plugin list

4)删除插件

./bin/elasticsearch-plugin remove analysis-icu

二、analysis-ik分词器 

analysis-ik 是一个基于 IK Analyzer 的中文分词插件,IK 分词器是一个非常流行且高效的中文分词器,它基于词典和规则的方式进行中文分词,尤其适合处理中文文本。IK 分词器的优势是精确度高、性能优秀,特别适合中文文本分析。 

下载地址(注:要和elasticsearch版本一致):Index of: analysis-ik/stable/

下载完后加压直接放在根目录的plugins文件下,然后重启elasticsearch即可生效。(因为之前已经设置过volume持久化了,docker会自动同步到容器中 )

analysis-icu 和 analysis-ik 分词器的主要区别

特性analysis-icuanalysis-ik
语言支持支持多语言,特别适合多语言环境。专注于中文分词,支持中文分词的各种优化。
分词精度对于中文的精度较低,适合多语言环境。对于中文分词精度较高,适合中文文本分析。
适用场景多语言的文本分析,尤其是Unicode字符。主要用于中文语料库,精细化中文分词。
分词模式基于 ICU 字符库的分词器,语言无关。提供细粒度和粗粒度两种分词模式。
扩展性支持复杂的字符过滤和 Unicode 操作。支持用户自定义词典,适合特定行业的分词。
性能性能较为一般,适合多语言环境。高效,专为中文设计,性能优越。

示例

 在kibana左侧菜单management,开发工具中测试

# 创建索引
PUT /my-index

# 添加索引
POST /my-index/_doc
{
    "id": "park_rocky-mountain",
    "title": "Rocky Mountain",
    "description": "Bisected north to south by the Continental Divide, this portion of the Rockies has ecosystems varying from over 150 riparian lakes to montane and subalpine forests to treeless alpine tundra."
}

# 通过索引查询数据
GET /my-index/_search?q="rocky mountain"

# 使用icu分词器
POST /_analyze -H 'Content-Type: application/json' -d'
{
  "analyzer": "icu_analyzer",
  "text": "中华人民共和国"
}

# 默认分词会单字拆分
POST /_analyze -H 'Content-Type: application/json' -d'
{
  "analyzer": "standard",
  "text": "中华人民共和国"
}

# 使用ik粗粒度分词
POST /_analyze -H 'Content-Type: application/json' -d'
{
  "analyzer": "ik_smart",
  "text": "中华人民共和国"
}

# 使用ik细粒度分词
POST /_analyze -H 'Content-Type: application/json' -d'
{
  "analyzer": "ik_max_word",
  "text": "中华人民共和国"
}

在nodejs中连接elasticsearch(注:bun存在兼容性问,无法正确执行,deno,node可以),@elastic/elasticsearch文档:https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/getting-started-js.html#_indexing_documents

import { Client } from '@elastic/elasticsearch';


/**
 * 创建 Elasticsearch 客户端实例。
 * 注意:
 * - 在 elasticsearch.yml 配置文件中设置了 `xpack.security.enabled: false`,
 *   因此 Elasticsearch 不会进行账号密码验证。
 * - 虽然配置了 `elastic` 用户的密码,但在关闭安全验证的情况下,`auth` 参数可以不传。
 * - 并且这里设置的密码是错误的,elasticsearch是可以正常连接的。
 */
const client = new Client({
  node: 'http://localhost:9200',
  auth: {
    // 连接云端使用
    // apiKey: {
    //   id: 'foo',
    //   api_key: 'bar',
    // },
    username: 'elastic',
    password: 'elastic1234',
  },
});


// 创建索引
console.log(await client.indices.create({ index: 'my_index' }));

// 创建数据
console.log(await client.index({
  index: 'my_index',
  id: 'my_document_id',
  document: {
    foo: 'foo',
    bar: 'bar',
  },
}));

// 查询数据
console.log(await client.get({
  index: 'my_index',
  id: 'my_document_id',
}));

// 搜索数据
console.log(await client.search({
  query: {
    match: {
      foo: 'foo'
    }
  }
}));

// 修改数据
console.log(await client.update({
  index: 'my_index',
  id: 'my_document_id',
  doc: {
    foo: 'bar',
    new_field: 'new value'
  }
}));

// 删除数据
console.log(await client.delete({
  index: 'my_index',
  id: 'my_document_id',
}));

// 删除索引
console.log(await client.indices.delete({ index: 'my_index' }));

// 文本分析
// 定义分析文本的函数
async function analyzeText(analyzer, text) {
  try {
    const response = await client.indices.analyze({
      body: {
        analyzer: analyzer,
        text: text,
      }
    });
    console.log(`Using analyzer: ${analyzer}`);
    console.log(response);
  } catch (error) {
    console.error(`Error using analyzer ${analyzer}:`, error);
  }
}

// 分析文本
async function performAnalysis() {
  // ICU 分词器分析
  await analyzeText('icu_analyzer', '中华人民共和国');

  // 标准分词器分析
  await analyzeText('standard', '中华人民共和国');

  // IK 粗粒度分词器分析
  await analyzeText('ik_smart', '中华人民共和国');

  // IK 细粒度分词器分析
  await analyzeText('ik_max_word', '中华人民共和国');
}

// 执行分析
performAnalysis();

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

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

相关文章

Jenkins整合Jmeter实现接口自动化测试

🍅 点击文末小卡片,免费获取软件测试全套资料,资料在手,涨薪更快 一、安装jmeter 下载:http://jmeter.apache.org/download_jmeter.cgi 这里我用了一台Windows安装jmeter用来写接口测试的脚本,启动前修改j…

宇树科技13家核心零部件供应商梳理!

2025年2月6日,摩根士丹利(Morgan Stanley)发布最新人形机器人研报:Humanoid 100: Mapping the Humanoid Robot Value Chain(人形机器人100:全球人形机器人产业链梳理)。 Humanoid 100清单清单中…

PostgreSQL 与 MySQL 有哪些区别

PostgreSQL 和 MySQL 是两种流行的开源关系型数据库管理系统(RDBMS),它们在功能、性能、扩展性和适用场景等方面存在显著差异。 以下是 PostgreSQL 和 MySQL 的主要区别: 1. 架构与设计理念 PostgreSQL: 强调标准兼…

springboot整合 xxl-job

文章目录 一、xxl-job是什么二、使用步骤 1. 下载并运行管理端代码2. 访问管理页面,确认是否启动成功3. 配置执行器【在自己的springboot项目中配置】4. 在页面上创建执行器和任务,与项目中绑定 总结参考 一、xxl-job是什么 XXL-JOB 是一个分布式任务调…

conda、anaconda、pip、pytorch、tensorflow有什么区别?

先画一张图,可以大致看出它们的区别和关联: pytorch、tensorflow都是Python的第三方库,相当于封装的代码工具集库,通过import导入使用。这两个都是深度学习框架,用来搭建AI模型什么的,使用范围非常之广&…

java后端开发day18--学生管理系统

(以下内容全部来自上述课程) 1.业务分析并搭建主菜单 1.需求 采取控制台的方式去书写学生管理系统 2.分析 1.初始菜单 2.学生类 属性:id,姓名,年龄,家庭住址 3.添加功能 键盘录入每一个学生信息并添…

【设计模式精讲】结构型模式之代理模式(静态代理、JDK动态代理、cglib动态代理)

文章目录 第五章 结构型模式5.1 代理模式5.1.1 代理模式介绍5.1.2 代理模式原理5.1.3 静态代理实现5.1.4 JDK动态代理5.1.4.1 JDK动态代理实现5.1.4.2 类是如何动态生成的5.1.4.3 代理类的调用过程 5.1.5 cglib动态代理5.1.5.1 cglib动态代理实现5.1.5.2 cglib代理流程 5.1.6 代…

业务流程中的流程管理

流程管理是业务流程管理中至关重要的一环。它专注于规划、组织、指导、控制和优化组织内的各项业务流程,以提高效率、降低成本、提升质量和增强客户满意度。简单来说,流程管理就是管理你的业务是如何完成工作的。 下面将从几个方面详细讲解业务流程中的…

2025年股指期货和股指期权合约交割的通知!

锦鲤三三每日分享期权知识,帮助期权新手及时有效地掌握即市趋势与新资讯! 2025年股指期货和股指期权合约交割的通知! 根据中国金融期货交易所规则及相关规定,以下股指期货和股指期权合约于指定日期进行交割,现将各合…

播放器系列1——总概述

播放器核心架构 模块解释 文件读取 读取视频文件、读取网络文件、读取音频文件,大概分为这三种,目前代码中仅实现了读取视频文件播放,也就是当没有video数据的时候播放器不可使用。 解复用 容器指的是多媒体文件中的封装格式,…

MacOS下使用Ollama本地构建DeepSeek并使用本地Dify构建AI应用

目录 1 大白话说一下文章内容2 作者的电脑配置3 DeepSeek的本地部署3.1 Ollamal的下载和安装3.2 选择合适的deepseek模型3.3 安转deepseek 4 DifyDeepSeek构建Al应用4.1 Dify的安装4.1.1 前置条件4.1.2 拉取代码4.1.3 启动Dify 4.2 Dify控制页面4.3 使用Dify实现个“文章标题生…

神经网络八股(三)

1.什么是梯度消失和梯度爆炸 梯度消失是指梯度在反向传播的过程中逐渐变小,最终趋近于零,这会导致靠前层的神经网络层权重参数更新缓慢,甚至不更新,学习不到有用的特征。 梯度爆炸是指梯度在方向传播过程中逐渐变大,…

第3章 3.3日志 .NET Core日志 NLog使用教程

3.3.1 .NET Core日志基本使用 书中介绍了把日志输出到控制台的使用方式: 安装 Microsoft.Extensions.Logging 和 Microsoft.Extensions.Logging.Console 日志记录代码: using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.…

Springboot的jak安装与配置教程

目录 Windows系统 macOS系统 Linux系统 Windows系统 下载JDK: 访问Oracle官网或其他JDK提供商网站,下载适合Windows系统的JDK版本。网站地址:Oracle 甲骨文中国 | 云应用和云平台点击进入下滑,点击进入下载根据自己的系统选择&…

Vue2是如何利用Object.defineProperty实现数据的双向绑定?

我们之前说道过Object.defineProperty方法有一关键特性,就是数据劫持,通过get/set 拦截属性的读取和修改操作。Vue主要是通过数据劫持结合发布-订阅模式来实现的,利用Object.defineProperty来劫持各个属性的setter和getter,在数据…

Transformer解析——(四)Decoder

本系列已完结,全部文章地址为: Transformer解析——(一)概述-CSDN博客 Transformer解析——(二)Attention注意力机制-CSDN博客 Transformer解析——(三)Encoder-CSDN博客 Transforme…

Vue前端开发-Vant之Layout组件

在Vant 中,Layout组件用于元素的响应式布局,分别由van-row和van-col两个组件来实现,前者表示行,后者被包裹在van-row组件中,表示列,共有24列栅格组成,在van-col组件中,span属性表示所…

【YOLOv8】损失函数

学习视频: yolov8 | 损失函数 之 5、类别损失_哔哩哔哩_bilibili yolov8 | 损失函数 之 6、定位损失 CIoU DFL_哔哩哔哩_bilibili 2.13、yolov8损失函数_哔哩哔哩_bilibili YOLOv8 的损失函数由类别损失和定位损失构成 类别损失:BCE Loss 定位损失…

Mac系统下使用Docker快速部署MaxKB:打造本地知识库问答系统

随着大语言模型的广泛应用,知识库问答系统逐渐成为提升工作效率和个人学习的有力工具。MaxKB是一款基于LLM(Large Language Model)大语言模型的知识库问答系统,支持多模型对接、文档上传和自动爬取等功能。本文将详细介绍如何在Ma…

(Arxiv-2025)ImageRAG:用于参考引导图像生成的动态图像检索

ImageRAG:用于参考引导图像生成的动态图像检索 paper是Tel Aviv University发布在Arxiv 2025的工作 paper title:ImageRAG: Dynamic Image Retrieval for Reference-Guided Image Generation Code:链接 图 1:使用参考图像扩展图像生成模型的生成能力。 在…