node.js + @elastic/elasticsearch 操作elasticsearch数据库

我这边node.js 使用的是 koa2,elasticsearch是8.11.1版本

官网:https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/getting-started-js.html

一、@elastic/elasticsearch 连接 elasticsearch数据库

如果elasticsearch没有设置账号秘密 则auth就不需要了

复制代码
const { Client } = require('@elastic/elasticsearch');
this.elastic = new Client({
  node: 'http://localhost:9200',
  auth: {
	    username: 'xm',
	    password: '123'  
    }
});

// 另一个写法
const elastic = new Client({
  node: 'https://username:password@localhost:9200'
})

二、基础操作

1、创建

1)创建一条信息

复制代码
this.elastic.index({
 index: 'testes',
 id: '20240425-01',
  body: {
    name: 'xiaoming',
    age: 22
  }
})

创建一条信息,id不填 系统会自动补全

注意:index 只能是小写,不能大写,否则会报错,可以 'test-es'命名

2)批量创建

复制代码
await this.elastic.indices.create({
 index: 'tweets',
  operations: {
    mappings: {
      properties: {
        id: { type: 'integer' },
        text: { type: 'text' },
        user: { type: 'keyword' },
        time: { type: 'date' }
      }
    }
  }
}, { ignore: [400] })
const dataset = [
 {
    id: 1,
    text: 'If I fall, don\'t bring me back.',
    user: 'jon',
    time: new Date()
  },
  {
    id: 2,
    text: 'Winter is coming',
    user: 'ned',
    time: new Date()
  },
  {
    id: 3,
    text: 'A Lannister always pays his debts.',
    user: 'tyrion',
    time: new Date()
  },
  {
    id: 4,
    text: 'I am the blood of the dragon.',
    user: 'daenerys',
    time: new Date()
  },
  {
    id: 5, // change this value to a string to see the bulk response with errors
    text: 'A girl is Arya Stark of Winterfell. And I\'m going home.',
    user: 'arya',
    time: new Date()
  }
]

const operations = dataset.flatMap(doc => [{ index: { _index: 'tweets' } }, doc])

const bulkResponse = await this.elastic.bulk({ refresh: true, operations })
const count = await this.elastic.count({ index: 'tweets' })
console.log(count)

等同于

复制代码
await this.elastic.bulk({
  refresh: true,
  operations: [
    // operation to perform
    { index: { _index: 'game-of-thrones' } },
    // the document to index
    {
      character: 'Ned Stark1',
      quote: 'Winter is coming1.'
    },

    { index: { _index: 'game-of-thrones' } },
    {
      character: 'Daenerys Targaryen2',
      quote: 'I am the blood of the dragon2.'
    },

    { index: { _index: 'game-of-thrones' } },
    {
      character: 'Tyrion Lannister3',
      quote: 'A mind needs books like a sword needs a whetstone3.'
    }
  ]
});

根据官网来看,bulk其实就是批量操作,这里也可以 update、delete 等等

2、删除

1)删除单个

复制代码
this.elastic.delete({
  index: 'testes',
  id: '20240425-01'
});

2)按条件删除,会删除符合条件的所有数据

复制代码
this.elastic.deleteByQuery({
  index: 'tweets',
  query: {
    match: {user: 'tyrion'}
  }
})

3、更新操作

复制代码
await this.elastic.update({
 index: 'tweets',
  id: 'QK5KE48BTvD5VO_sox9p',
  doc: {
    text: '111',
    user: '222'
  }
});
const document = await this.elastic.get({
  index: 'tweets',
  id: 'QK5KE48BTvD5VO_sox9p'
});

4、查询操作

1)单个查询,根据 index 和 id精准查询

复制代码
const document = await this.elastic.get({
  index: 'tweets',
  id: 'QK5KE48BTvD5VO_sox9p'
});

2)查询所有,查询 index 为 testes 的所有数值

复制代码
this.elastic.search({
  index: 'testes'
})

3)search 混合查询

复制代码
GET /cartest/_search
{
 "size": 10,
 "from": 0,
 "query":{
    "bool":{
    "must":[
      {
        "match":{
          "say": "33333"
        }
      },
      {
        "regexp": {
          "name": ".*云.*" 
        }
      },
      {
        "range": {
          "num": {
            "gte": 120,
            "lte": 200
          }
        }
      }
    ]
   }
 }
}

具体查询大家可以看我这个文章:query 中的内容大致都是一致的

https://blog.csdn.net/weixin_44384273/article/details/137920183?spm=1001.2014.3001.5501

相关推荐
范什么特西7 小时前
回答知识总结04(redis)
数据库·redis·缓存
码农颜8 小时前
5.4.1 锁分类
java·数据库·mysql
云深处@8 小时前
【数据库】MySQL 入门
数据库·学习·mysql
梦远星帆8 小时前
SQLyog社区版下载
数据库·mysql·sqlyog
互联网中的一颗神经元9 小时前
09 — .git 地图:打开那个隐藏文件夹
大数据·git·elasticsearch
科力锐品牌君10 小时前
行业龙头|科力锐全链路防勒索 + 多中心容灾方案,构筑河南翔宇医疗业务安全闭环!
网络·数据库·分布式·安全·数据安全·备份
zyplayer-doc10 小时前
zyplayer-doc企业知识库能做什么:从文档创建、权限管理到AI问答的完整能力
大数据·javascript·数据库·人工智能·pdf·word
会编程的吕洞宾12 小时前
LangChain4j Tool Calling 实战:让大模型自动查数据库发邮件,一句话搞定复杂任务
数据库·人工智能
独行侠影a12 小时前
Elasticsearch海量数据查询优化:深度分页与聚合查询提速方案
大数据·elasticsearch·搜索引擎
知行合一。。。13 小时前
DeepAgents--01--Agent和OpenClaw的相关概念
android·数据库