← 返回资讯

序奏资讯

elasticsearch 分词

在 Elasticsearch 中使用停用词(Stop Words)进行分词时,通常需要在自定义分析器(Analyzer)中配置停用词过滤器(Stop Token Filter)。以下是具体步骤: ### 1. 定义自定义分析器 你可以在索引设置中定义一个自定义分析器,并在其中使用停用词过滤器。 ```json PUT /my_index { "settin

在 Elasticsearch 中使用停用词(Stop Words)进行分词时,通常需要在自定义分析器(Analyzer)中配置停用词过滤器(Stop Token Filter)。以下是具体步骤:

### 1. 定义自定义分析器
你可以在索引设置中定义一个自定义分析器,并在其中使用停用词过滤器。

```json
PUT /my_index
{
  "settings": {
    "analysis": {
      "analyzer": {
        "my_custom_analyzer": {
          "type": "custom",
          "tokenizer": "standard",
          "filter": [
            "lowercase",
            "my_stop_filter"
          ]
        }
      },
      "filter": {
        "my_stop_filter": {
          "type": "stop",
          "stopwords": ["a", "an", "the", "and", "or", "but"]
        }
      }
    }
  }
}
```

### 2. 使用自定义分析器
定义好分析器后,可以在字段映射中使用它。

```json
PUT /my_index/_mapping
{
  "properties": {
    "content": {
      "type": "text",
      "analyzer": "my_custom_analyzer"
    }
  }
}
```

### 3. 测试分析器
你可以使用 `_analyze` API 测试分析器的效果。

```json
GET /my_index/_analyze
{
  "analyzer": "my_custom_analyzer",
  "text": "This is a test of the stop words filter"
}
```

### 4. 使用预定义的停用词列表
Elasticsearch 提供了一些预定义的停用词列表,如 `_english_`、`_french_` 等。

```json
PUT /my_index
{
  "settings": {
    "analysis": {
      "analyzer": {
        "my_custom_analyzer": {
          "type": "custom",
          "tokenizer": "standard",
          "filter": [
            "lowercase",
            "my_stop_filter"
          ]
        }
      },
      "filter": {
        "my_stop_filter": {
          "type": "stop",
          "stopwords": "_english_"
        }
      }
    }
  }
}
```

### 5. 从文件中加载停用词
你也可以从文件中加载停用词列表。

```json
PUT /my_index
{
  "settings": {
    "analysis": {
      "analyzer": {
        "my_custom_analyzer": {
          "type": "custom",
          "tokenizer": "standard",
          "filter": [
            "lowercase",
            "my_stop_filter"
          ]
        }
      },
      "filter": {
        "my_stop_filter": {
          "type": "stop",
          "stopwords_path": "config/stopwords.txt"
        }
      }
    }
  }
}
```

### 总结
通过自定义分析器和停用词过滤器,你可以在 Elasticsearch 中有效地去除停用