# Node.js 用法

URL: https://caijiao.org/elasticsearch/04.practical/06.client-nodejs
Source: docs/elasticsearch/04.practical/06.client-nodejs.md
Description: 本章介绍如何在 Node.js 环境中安装和使用官方 Elasticsearch 客户端，实现索引管理、文档操作和查询功能。

Elasticsearch 提供官方 Node.js 客户端，方便 JavaScript 开发者在 Node.js 环境下与 Elasticsearch 集群交互，支持丰富的 API 功能。

## 1. 安装客户端

使用 npm 安装：

```bash
npm install @elastic/elasticsearch
````

## 2. 客户端初始化示例

```js
const { Client } = require('@elastic/elasticsearch');

const client = new Client({ node: 'http://localhost:9200' });

async function run() {
  // 检查集群状态
  const health = await client.cluster.health();
  console.log('Cluster health:', health.body.status);
}

run().catch(console.log);
```

## 3. 基本操作示例

### 创建索引

```js
async function createIndex() {
  await client.indices.create({ index: 'my-index' }).catch(err => {
    if (err.meta.body.error.type === 'resource_already_exists_exception') {
      console.log('Index already exists');
    } else {
      throw err;
    }
  });
}
```

### 添加文档

```js
async function addDocument() {
  const response = await client.index({
    index: 'my-index',
    document: {
      title: 'Elasticsearch 教程',
      content: '这是一个简单的 Elasticsearch 示例',
      date: '2025-07-01'
    }
  });
  console.log(response);
}
```

### 查询文档

```js
async function search() {
  const result = await client.search({
    index: 'my-index',
    query: {
      match: { content: '示例' }
    }
  });
  console.log(result.hits.hits);
}
```

## 4. 注意事项

* 确保客户端版本与 Elasticsearch 服务器兼容
* 处理异步异常和连接问题
* 利用官方文档跟踪最新功能和最佳实践

---

使用官方 Node.js 客户端，可以轻松构建基于 Elasticsearch 的强大搜索和分析应用。
