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

news2025/4/12 21:39:18

使用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();

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

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

相关文章

封装一个vue3控制并行任务数量的组合式函数

一. 使用场景 使用环境: vue3 当需要处理多个异步任务时,想要控制并行异步任务的数量,不想所有任务同时执行导致产生性能上的问题, 比如当需要同时发起多个网络请求,但又不想一次性发出过多请求导致服务器压力过大或…

SpringSecurity请求流转的本质

1. SpringSecurity核心源码分析 分析SpringSecurity的核心原理,那么我们从哪开始分析?以及我们要分析哪些内容? 系统启动的时候SpringSecurity做了哪些事情?第一次请求执行的流程是什么?SpringSecurity中的认证流程是怎么样的?1.1 系统启动 当我们的Web服务启动的时候,…

【AI工具之Deepseek+Kimi一键免费生成PPT】

1.打开Deepseek网页:DeepSeek 2.使用Deepseek获得一份PPT大纲(输入背景需求约束条件进行提问)如下图: 3.复制Deepseek输出的PPT大纲 4.打开Kimi网页:Kimi.ai - 会推理解析,能深度思考的AI助手 5.在Kimi中…

基于微信小程序的宿舍报修管理系统设计与实现,SpringBoot(15500字)+Vue+毕业论文+指导搭建视频

运行环境 jdkmysqlIntelliJ IDEAmaven3微信开发者工具 项目技术SpringBoothtmlcssjsjqueryvue2uni-app 宿舍报修小程序是一个集中管理宿舍维修请求的在线平台,为学生、维修人员和管理员提供了一个便捷、高效的交互界面。以下是关于这些功能的简单介绍: …

DeepSeek 助力 Vue 开发:打造丝滑的右键菜单(RightClickMenu)

前言:哈喽,大家好,今天给大家分享一篇文章!并提供具体代码帮助大家深入理解,彻底掌握!创作不易,如果能帮助到大家或者给大家一些灵感和启发,欢迎收藏关注哦 💕 目录 Deep…

WLAN无线2.4G/5G频段划分和可用信道

互联网各领域资料分享专区(不定期更新): Sheet

自己安装一台DeepSeek的服务器

找一台还可以的Linux服务器,登录后执行: curl -fsSL https://ollama.com/install.sh | sh 等待安装完成: 执行命令,根据服务器能力安装不同版本的AI模型: ollama run llama3.2 下一步就开始对话吧: llam…

StableDiffusion学习笔记——4、模型下载和学习

目录   大家好,我是阿赵。   继续学习StableDiffusion的使用。   这次来学习一下模型的相关知识 一、 什么是模型 之前我们了解过,在StableDiffusion里面生成图片或者视频,都需要先选择模型。模型用通俗的话来说,就是决定了…

微软宣布 Windows 11 将不再免费升级:升级需趁早

大家都知道如果你现在是Windows 10 系统,其实可以免费升级到正版 Windows 11,只要你的电脑配置满足 TPM2.0要求。 而最近微软已经公布了 Windows 10 的最后支持时间,也就是今年10月14日,在这之后微软将不再对Windows 10负责&#…

Java开发实习面试笔试题(含答案)

在广州一家中大公司面试(BOSS标注是1000-9999人,薪资2-3k),招聘上写着Java开发,基本没有标注前端要求,但是到场知道是前后端分离人不分离。开始先让你做笔试(12道问答4道SQL题)&…

解析DrugBank数据库数据|Python

一、DrugBank 数据库简介 DrugBank 是一个综合性的生物信息学和化学信息学数据库,专门收录药物和靶点的详细信息。它由加拿大阿尔伯塔大学的 Wishart 研究组 维护,提供化学、药理学、相互作用、代谢、靶点等多方面的药物数据。DrugBank 结合了实验数据和…

专题 - Java Stream API

概述 分类 数据源 任何位置。 如:集合、数组、文件、随机数、 Stream 静态工厂等。 支持的数据类型 整型、长整型、双精度浮点型基本数据类型。引用数据类型。流管道的数据处理流程 流管道必须要有终止操作。否则永不执行,只是一个静默的无操作指令。流管道是懒运算的。当执…

【前端框架】vue2和vue3的区别详细介绍

Vue 3 作为 Vue 2 的迭代版本,在性能、语法、架构设计等多个维度均有显著的变革与优化。以下详细剖析二者的区别: 响应式系统 Vue 2 实现原理:基于 Object.defineProperty() 方法实现响应式。当一个 Vue 实例创建时,Vue 会遍历…

大模型WebUI:Gradio全解11——使用transformers.agents构建Gradio UI(3)

大模型WebUI:Gradio全解11——使用transformers.agents构建Gradio UI(3) 前言本篇摘要11. 使用transformers.agents构建Gradio UI11.3 创建和使用工具Tools11.3.1 默认工具箱与load_tool11.3.2 创建新工具11.3.3 管理代理的工具箱toolbox11.3…

路由基础 | 路由引入实验 | 不同路由引入方式存在的问题

注:本文为 “路由基础 | 路由表 | 路由引入” 相关文章合辑。 未整理去重。 路由基本概念 1—— 路由表信息、路由进表以及转发流程、最长掩码匹配原则 静下心来敲木鱼已于 2023-11-26 14:06:22 修改 什么是路由 路由就是指导报文转发的路径信息,可以…

网络原理-HTTP/HTTPS

文章目录 HTTPHTTP 是什么?理解“应用层协议”理解 HTTP 协议的⼯作过程HTTP 协议格式抓包⼯具的使用抓包⼯具的原理抓包结果协议格式总结 HTTP 请求(Request)认识 URLURL 的基本格式关于URL encode 认识“⽅法”(method&#xff…

SpringBoot启动失败之application.yml缩进没写好

修改前: spring前面空格了 报错输出:Failed to configure a DataSource: ‘url’ attribute is not specified and no embedded datasource could be configured. Reason: Failed to determine a suitable driver class Action: Consider the follow…

python爬虫系列课程2:如何下载Xpath Helper

python爬虫系列课程2:如何下载Xpath Helper 一、访问极简插件官网二、点击搜索按钮三、输入xpath并点击搜索四、点击推荐下载五、将下载下来的文件解压缩六、打开扩展程序界面七、将xpath.crx文件拖入扩展程序界面一、访问极简插件官网 极简插件官网地址:https://chrome.zzz…

CentOS建立ssh免密连接(含流程剖析)

一、场景举例(为啥需要免密连接) 1.服务集群间文件复制、通信 2.执行定时触发自动化脚本 3.本地连接远程服务器操作 服务器台数有很多,以上举例都是属于服务器之间的通信,如果每次执行上面操作都要输入账号密码岂不是效率太高了,容易被开…

自由学习记录(36)

Linux Linux 是一个开源的操作系统,其内核及大部分组件都遵循自由软件许可证(如 GPL),允许用户查看、修改和分发代码。这种开放性使得开发者和企业可以根据自己的需求定制系统​。 “Linux”严格来说只是指由Linus Torvalds最初开…