Skip to content

Node.js ES 搜索进阶

批量生成假数据

bash
npm install @faker-js/faker
js
import { faker } from '@faker-js/faker'

// bulk 批量写入
const operations = []
for (let i = 0; i < 1000; i++) {
  operations.push(
    { index: { _index: 'articles', _id: i } },
    {
      title: faker.lorem.sentence(),
      content: faker.lorem.paragraphs(),
      author: faker.person.fullName(),
      tags: faker.helpers.arrayElements(['node', 'react', 'vue', 'python'], 2),
      createdAt: faker.date.past()
    }
  )
}
await client.bulk({ operations })

高级搜索

多字段搜索

js
await client.search({
  index: 'articles',
  query: {
    multi_match: { query: 'node.js', fields: ['title^3', 'content'] }  // title 权重 3x
  }
})

过滤 + 排序

js
await client.search({
  index: 'articles',
  query: {
    bool: {
      must: { match: { content: 'node' } },
      filter: { term: { 'tags.keyword': 'react' } }
    }
  },
  sort: [{ createdAt: 'desc' }],
  from: 0,
  size: 10
})

聚合统计

js
await client.search({
  index: 'articles',
  aggs: {
    by_author: {
      terms: { field: 'author.keyword', size: 10 }
    }
  }
})
// → 按作者分组统计文章数

// 平均值
aggs: { avg_score: { avg: { field: 'score' } } }

分词搜索

js
// 测试分词效果
const result = await client.indices.analyze({
  index: 'articles',
  text: 'Node.js 全栈开发'
})
console.log(result.tokens)  // ['node', 'js', '全栈', '开发']

常用查询类型

查询说明
match分词匹配
term精确匹配(不分词)
multi_match多字段搜索
fuzzy模糊/纠错搜索
range范围搜索(时间/数值)
bool组合条件(must/should/filter)