Docker 部署 Elasticsearch 8.19.10 版本,已集成 IK 中文分词插件。单节点模式运行,默认禁用安全认证。

docker run -d -p 9200:9200 -e discovery.type=single-node -e xpack.security.enabled=false docker-elasticsearch

中文分词功能

IK 插件提供两种分词模式:

  • ik_max_word:细粒度分词,尽可能拆分为更多词语
  • ik_smart:粗粒度分词,保持最简分词结果

分词测试示例:

curl -X POST "localhost:9200/_analyze" -H "Content-Type: application/json" -d '{"analyzer": "ik_max_word", "text": "测试文本"}'

Python 客户端操作

安装异步客户端:

pip install elasticsearch[async]

建立连接:

from elasticsearch import AsyncElasticsearch
es = AsyncElasticsearch(["http://localhost:9200"])

索引创建示例(含IK配置):

await es.indices.create(
    index="docs",
    settings={
        "analysis": {
            "analyzer": {
                "ik_analyzer": {
                    "type": "custom",
                    "tokenizer": "ik_max_word"
                }
            }
        }
    },
    mappings={
        "properties": {
            "content": {"type": "text", "analyzer": "ik_max_word"},
            "timestamp": {"type": "date"}
        }
    }
)

文档CRUD操作

插入单文档:

await es.index(
    index="docs",
    id="doc1",
    document={"content": "示例内容", "timestamp": "2026-01-01"}
)

批量插入:

from elasticsearch.helpers import async_bulk
actions = [
    {"_index": "docs", "_id": i, "_source": {"content": f"内容{i}"}}
    for i in range(10)
]
await async_bulk(es, actions)

复合查询:

result = await es.search(
    index="docs",
    query={
        "bool": {
            "must": {"match": {"content": "重要"}},
            "filter": {"range": {"timestamp": {"gte": "2026-01-01"}}}
        }
    }
)

向量搜索功能

创建向量索引:

await es.indices.create(
    index="vec_index",
    mappings={
        "properties": {
            "embedding": {
                "type": "dense_vector",
                "dims": 768,
                "index": True,
                "similarity": "cosine"
            }
        }
    }
)

KNN搜索:

await es.search(
    index="vec_index",
    knn={
        "field": "embedding",
        "query_vector": [0.1]*768,
        "k": 5,
        "num_candidates": 50
    }
)

索引管理

查看索引列表:

await es.cat.indices(format="json")

删除索引:

await es.indices.delete(index="docs")

关闭客户端连接:

await es.close()

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐