Elasticsearch 创建索引方法
-
使用 REST API 创建索引
- 请求方法:PUT
- URL示例:
PUT /
- 示例请求:
curl -X PUT "http://localhost:9200/my_index" -H 'Content-Type: application/json' -d' { "settings": { "number_of_shards": 3, "number_of_replicas": 2 }, "mappings": { "properties": { "field1": { "type": "text" }, "field2": { "type": "keyword" }, "field3": { "type": "date" } } } }'
-
使用 Kibana Dev Tools 创建索引
- 步骤:打开Kibana Dev Tools,输入PUT请求并运行。
-
自动创建索引
- 如果发送文档到不存在的索引,Elasticsearch会自动创建该索引。
-
使用 Elasticsearch 客户端创建索引
- 语言示例(Python):
from elasticsearch import Elasticsearch es = Elasticsearch("http://localhost:9200") index_config = { "settings": { "number_of_shards": 3, "number_of_replicas": 2 }, "mappings": { "properties": { "field1": {"type": "text"}, "field2": {"type": "keyword"}, "field3": {"type": "date"} } } } response = es.indices.create(index="my_index", body=index_config) print(response)
- 语言示例(Python):
创建索引映射
-
示例映射创建请求:
curl -X PUT "http://localhost:9200/questions_index" -H 'Content-Type: application/json' -d' { "settings": { "number_of_shards": 1, "number_of_replicas": 1 }, "mappings": { "properties": { "zhangjie": { "type": "text", "fields": { "keyword": { "type": "keyword" } } }, "content": { "type": "text" }, "zhishidian": { "type": "text", "fields": { "keyword": { "type": "keyword" } } }, "answer": { "type": "keyword" } } } }'
-
示例文档插入:
curl -X POST "http://localhost:9200/questions_index/_doc/1" -H 'Content-Type: application/json' -d' { "zhangjie": "第2章 物理层", "content": "
在异步通信中,每个字符包含1位起始位、7位数据位、1位奇偶位和1位终止位,每秒钟传送200个字符,采用4相位调制,则码元速率为()。
", "zhishidian": "概述 - 计算机网络在信息时代中的作用", "answer": "1000波特" }'
Python 脚本读取 JSON 文件并上传
-
示例 JSON 文件 (data.json):
[ { "zhangjie": "第2章 物理层", "content": "
在异步通信中,每个字符包含1位起始位、7位数据位、1位奇偶位和1位终止位,每秒钟传送200个字符,采用4相位调制,则码元速率为()。
", "zhishidian": "概述 - 计算机网络在信息时代中的作用", "answer": "1000波特" }, { "zhangjie": "第8章 网络安全", "content": "在TCP/IP协议栈中,安全的远程登录采用的协议为()。
", "zhishidian": "概述 - 计算机网络在信息时代中的作用", "answer": "SSH" } ] -
Python 脚本:
import json from elasticsearch import Elasticsearch, helpers es = Elasticsearch("http://localhost:9200") index_name = "questions_index" def read_json_file(file_path): with open(file_path, "r", encoding="utf-8") as f: return json.load(f) def upload_data_to_elasticsearch(data, index): actions = [ { "_index": index, "_source": record } for record in data ] helpers.bulk(es, actions) print(f"已成功上传 {len(actions)} 条记录到索引 {index}") if __name__ == "__main__": file_path = "data.json" try: data = read_json_file(file_path) if not es.indices.exists(index=index_name): es.indices.create(index=index_name) print(f"索引 {index_name} 已创建。") upload_data_to_elasticsearch(data, index_name) except Exception as e: print(f"发生错误: {e}")
-
运行脚本:
- 确保安装 elasticsearch 包:
pip install elasticsearch
- 运行命令:
python upload_to_elasticsearch.py
- 确保安装 elasticsearch 包: