ElasticSearch快速入门

ElasticSearch

概念

Elasticsearch(简称 ES)是一个开源的分布式搜索和分析引擎,被广泛运用于全文检索、日志分析、安全监控和人工智能应用中。它旨在帮助用户从海量数据中快速、近乎实时地获取有价值的洞察。

要理解 Elasticsearch,可以抓住以下几个核心概念:

概念 通俗类比 简要说明
索引 (Index) 数据库中的“库”或“表” 拥有相似结构文档的集合,是检索和管理数据的逻辑单元。
文档 (Document) 表中的一行数据 搜索和存储的最小数据单元,格式为灵活的 JSON 对象。
节点 (Node) 集群中的一台服务器 集群中的一个服务器实例,用于存储数据并参与集群的索引与搜索功能。
集群 (Cluster) 多台服务器组成的整体 由一个或多个节点组成,对外提供统一服务,数据在整个集群中分布式存储。
分片 (Shard) 将数据切分成多块 索引被拆分为多个分片,分布在不同节点上,实现水平扩展和并行处理。
副本 (Replica) 数据的备份 分片的完整拷贝,用于提高数据可用性和搜索的并发吞吐量。

ELK 是 Elasticsearch、Logstash、Kibana 三个开源组件的首字母缩写,组合起来形成一套日志收集、存储、分析、可视化的完整解决方案。它的核心价值是:让散落在各台服务器上的日志被集中管理,并且能快速搜索和分析。

安装(linux)

# 以 arch为例

paru -S elasticsearch
paru -S kibana

配置

Kibana 是一个开源的数据可视化和探索工具,专门用于对存储在 Elasticsearch 中的数据进行搜索、分析和图表展示。

简单理解它的角色:

  • Elasticsearch = 存放大量数据的搜索引擎(后端)

  • Kibana = 用户操作数据的图形化界面(前端)

  • 配置elasticsearch:

# ======================== Elasticsearch Configuration =========================
#
# NOTE: Elasticsearch comes with reasonable defaults for most settings.
#       Before you set out to tweak and tune the configuration, make sure you
#       understand what are you trying to accomplish and the consequences.
#
# The primary way of configuring a node is via this file. This template lists
# the most important settings you may want to configure for a production cluster.
#
# Please consult the documentation for further information on configuration options:
# https://www.elastic.co/guide/en/elasticsearch/reference/index.html
#
# ---------------------------------- Cluster -----------------------------------
#
# Use a descriptive name for your cluster:
#
cluster.name: elasticsearch
#
# ------------------------------------ Node ------------------------------------
#
# Use a descriptive name for the node:
#
#node.name: node-1
#
# Add custom attributes to the node:
#
#node.attr.rack: r1
#
# ----------------------------------- Paths ------------------------------------
#
# Path to directory where to store the data (separate multiple locations by comma):
#
path.data: /var/lib/elasticsearch
#
# Path to log files:
#
path.logs: /var/log/elasticsearch
#
# ----------------------------------- Memory -----------------------------------
#
# Lock the memory on startup:
#
#bootstrap.memory_lock: true
#
# Make sure that the heap size is set to about half the memory available
# on the system and that the owner of the process is allowed to use this
# limit.
#
# Elasticsearch performs poorly when the system is swapping the memory.
#
# ---------------------------------- Network -----------------------------------
#
# By default Elasticsearch is only accessible on localhost. Set a different
# address here to expose this node on the network:
#
network.host: 127.0.0.1
#
# By default Elasticsearch listens for HTTP traffic on the first free port it
# finds starting at 9200. Set a specific HTTP port here:
#
http.port: 9200
#
# For more information, consult the network module documentation.
#
# --------------------------------- Discovery ----------------------------------
#
# Pass an initial list of hosts to perform discovery when this node is started:
# The default list of hosts is ["127.0.0.1", "[::1]"]
#
#discovery.seed_hosts: ["host1", "host2"]
#
# Bootstrap the cluster using an initial set of master-eligible nodes:
#
#cluster.initial_master_nodes: ["node-1", "node-2"]
#
# For more information, consult the discovery and cluster formation module documentation.
#
# ---------------------------------- Various -----------------------------------
#
# Allow wildcard deletion of indices:
#
#action.destructive_requires_name: false

#----------------------- BEGIN SECURITY AUTO CONFIGURATION -----------------------
#
# The following settings, TLS certificates, and keys have been automatically      
# generated to configure Elasticsearch security features on 04-06-2026 02:39:18
#
# --------------------------------------------------------------------------------

# Enable security features
xpack.security.enabled: false

xpack.security.enrollment.enabled: false

# Enable encryption for HTTP API client connections, such as Kibana, Logstash, and Agents
xpack.security.http.ssl:
  enabled: false
  # keystore.path: certs/http.p12

# Enable encryption and mutual authentication between cluster nodes
xpack.security.transport.ssl:
  enabled: false
  # verification_mode: certificate
  # keystore.path: certs/transport.p12
  # truststore.path: certs/transport.p12
# Create a new cluster with the current node only
# Additional nodes can still join the cluster later
cluster.initial_master_nodes: ["archlinux"]

# Allow HTTP API connections from anywhere
# Connections are encrypted and require user authentication
http.host: 0.0.0.0

# Allow other nodes to join the cluster from anywhere
# Connections are encrypted and mutually authenticated
#transport.host: 0.0.0.0

#----------------------- END SECURITY AUTO CONFIGURATION -------------------------

  • kibana
# For more configuration options see the configuration guide for Kibana in
# https://www.elastic.co/guide/index.html

# =================== System: Kibana Server ===================
# Kibana is served by a back end server. This setting specifies the port to use.
server.port: 5601

# Specifies the address to which the Kibana server will bind. IP addresses and host names are both valid values.
# The default is 'localhost', which usually means remote machines will not be able to connect.
# To allow connections from remote users, set this parameter to a non-loopback address.
server.host: "0.0.0.0"

# Enables you to specify a path to mount Kibana at if you are running behind a proxy.
# Use the `server.rewriteBasePath` setting to tell Kibana if it should remove the basePath
# from requests it receives, and to prevent a deprecation warning at startup.
# This setting cannot end in a slash.
#server.basePath: ""

# Specifies whether Kibana should rewrite requests that are prefixed with
# `server.basePath` or require that they are rewritten by your reverse proxy.
# Defaults to `false`.
#server.rewriteBasePath: false

# Specifies the public URL at which Kibana is available for end users. If
# `server.basePath` is configured this URL should end with the same basePath.
#server.publicBaseUrl: ""

# The maximum payload size in bytes for incoming server requests.
#server.maxPayload: 1048576

# The Kibana server's name. This is used for display purposes.
#server.name: "your-hostname"

# Block requests to specific routes (exact path match, evaluated before auth).
# server.excludeRoutes: ["/api/status"]

# =================== System: Kibana Server (Optional) ===================
# Enables SSL and paths to the PEM-format SSL certificate and SSL key files, respectively.
# These settings enable SSL for outgoing requests from the Kibana server to the browser.
#server.ssl.enabled: false
#server.ssl.certificate: /path/to/your/server.crt
#server.ssl.key: /path/to/your/server.key

# =================== System: Elasticsearch ===================
# The URLs of the Elasticsearch instances to use for all your queries.
elasticsearch.hosts: ["http://localhost:9200"]

# If your Elasticsearch is protected with basic authentication, these settings provide
# the username and password that the Kibana server uses to perform maintenance on the Kibana
# index at startup. Your Kibana users still need to authenticate with Elasticsearch, which
# is proxied through the Kibana server.
#elasticsearch.username: "kibana_system"
#elasticsearch.password: "pass"

# Kibana can also authenticate to Elasticsearch via "service account tokens".
# Service account tokens are Bearer style tokens that replace the traditional username/password based configuration.
# Use this token instead of a username/password.
# elasticsearch.serviceAccountToken: "my_token"

# Time in milliseconds to wait for responses from the back end or Elasticsearch. This value
# must be a positive integer.
#elasticsearch.requestTimeout: 30000

# The maximum number of sockets that can be used for communications with elasticsearch.
# Defaults to `800`.
#elasticsearch.maxSockets: 1024

# Specifies whether Kibana should use compression for communications with elasticsearch
# Defaults to `false`.
#elasticsearch.compression: false

# List of Kibana client-side headers to send to Elasticsearch. To send *no* client-side
# headers, set this value to [] (an empty list).
#elasticsearch.requestHeadersWhitelist: [ authorization ]

# Header names and values that are sent to Elasticsearch. Any custom headers cannot be overwritten
# by client-side headers, regardless of the elasticsearch.requestHeadersWhitelist configuration.
#elasticsearch.customHeaders: {}

# Time in milliseconds for Elasticsearch to wait for responses from shards. Set to 0 to disable.
#elasticsearch.shardTimeout: 30000

# =================== System: Elasticsearch (Optional) ===================
# These files are used to verify the identity of Kibana to Elasticsearch and are required when
# xpack.security.http.ssl.client_authentication in Elasticsearch is set to required.
#elasticsearch.ssl.certificate: /path/to/your/client.crt
#elasticsearch.ssl.key: /path/to/your/client.key

# Enables you to specify a path to the PEM file for the certificate
# authority for your Elasticsearch instance.
#elasticsearch.ssl.certificateAuthorities: [ "/path/to/your/CA.pem" ]

# To disregard the validity of SSL certificates, change this setting's value to 'none'.
elasticsearch.ssl.verificationMode: none

# =================== System: Logging ===================
# Set the value of this setting to off to suppress all logging output, or to debug to log everything. Defaults to 'info'
#logging.root.level: debug

# Enables you to specify a file where Kibana stores log output.
#logging.appenders.default:
#  type: file
#  fileName: /var/logs/kibana.log
#  layout:
#    type: json

# Example with size based log rotation
#logging.appenders.default:
#  type: rolling-file
#  fileName: /var/logs/kibana.log
#  policy:
#    type: size-limit
#    size: 256mb
#  strategy:
#    type: numeric
#    max: 10
#  layout:
#    type: json

# Logs queries sent to Elasticsearch.
#logging.loggers:
#  - name: elasticsearch.query
#    level: debug

# Logs http responses.
#logging.loggers:
#  - name: http.server.response
#    level: debug

# Logs system usage information.
#logging.loggers:
#  - name: metrics.ops
#    level: debug

# Enables debug logging on the browser (dev console)
#logging.browser.root:
#  level: debug

# =================== System: Other ===================
# The path where Kibana stores persistent data not saved in Elasticsearch. Defaults to data
#path.data: data

# Specifies the path where Kibana creates the process ID file.
#pid.file: /run/kibana/kibana.pid

# Set the interval in milliseconds to sample system and process performance
# metrics. Minimum is 100ms. Defaults to 5000ms.
#ops.interval: 5000

# Specifies locale to be used for all localizable strings, dates and number formats.
# Supported languages are the following: English (default) "en", Chinese "zh-CN", Japanese "ja-JP", French "fr-FR", German "de-DE".
#i18n.locale: "en"

# =================== Frequently used (Optional)===================

# =================== Saved Objects: Migrations ===================
# Saved object migrations run at startup. If you run into migration-related issues, you might need to adjust these settings.

# The number of documents migrated at a time.
# If Kibana can't start up or upgrade due to an Elasticsearch `circuit_breaking_exception`,
# use a smaller batchSize value to reduce the memory pressure. Defaults to 1000 objects per batch.
#migrations.batchSize: 1000

# The maximum payload size for indexing batches of upgraded saved objects.
# To avoid migrations failing due to a 413 Request Entity Too Large response from Elasticsearch.
# This value should be lower than or equal to your Elasticsearch cluster’s `http.max_content_length`
# configuration option. Default: 100mb
#migrations.maxBatchSizeBytes: 100mb

# The number of times to retry temporary migration failures. Increase the setting
# if migrations fail frequently with a message such as `Unable to complete the [...] step after
# 15 attempts, terminating`. Defaults to 15
#migrations.retryAttempts: 15

# =================== Search Autocomplete ===================
# Time in milliseconds to wait for autocomplete suggestions from Elasticsearch.
# This value must be a whole number greater than zero. Defaults to 1000ms
# unifiedSearch.autocomplete.valueSuggestions.timeout: 1000

# Maximum number of documents loaded by each shard to generate autocomplete suggestions.
# This value must be a whole number greater than zero. Defaults to 100_000
#unifiedSearch.autocomplete.valueSuggestions.terminateAfter: 100000

快速入门

​ kibana的默认端口号是5601,直接浏览器输入127.0.0.1:5601访问,然后接入本地的elasticsearch服务,端口号是9200.
​ 之后搜索框搜索dev tools,然后就可以图形化界面进行操作.

索引创建

这段代码创建一个名为 hotel 的索引,并定义其字段映射。

  • PUT /hotel向ES发送一个HTTP的PUT请求,创建一个叫hotel的索引.

  • mappings相当于关系型数据库的表结构定义.

  • properties是一个固定关键字,用来生命文档类型或索引内部包含那些字段,以及每个字段的类型和配置.

  • name/city/price是字段.其中的type代表其类型.

PUT /hotel
{
    "mappings":{
        "properties": {
            "name":{
                "type":"text"
            },
            "city":{
                "type":"keyword"
            },
            "price":{
                "type":"double"            }
        }
    }
}

添加数据

  • hotel指定要插入的索引
  • _doc是文档类型,ES 7.x之后固定写_doc
  • 001手动指定ID为001.指定的话,ES会自动生成随机ID
PUT /hotel/_doc/001
{
    "name":"大胖熊",
    "city":"杭州",
    "price":999.999
}
{
  "_index": "hotel",
  "_id": "001",
  "_version": 1,
  "result": "created",
  "_shards": {
    "total": 2,
    "successful": 1,
    "failed": 0
  },
  "_seq_no": 0,
  "_primary_term": 1
}

搜索文档

  1. 根据_id搜索文档
GET /hotel/_doc/001
  1. 根据普通字段进行搜索文档
GET /hotel/_search
{
    "query":{
        "term":{
            "city":{
                value:"杭州"
            }
        }
    }
}
{
  "took": 3,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 1,
      "relation": "eq"
    },
    "max_score": 0.2876821,
    "hits": [
      {
        "_index": "hotel",
        "_id": "001",
        "_score": 0.2876821,
        "_source": {
          "name": "大胖熊",
          "city": "杭州",
          "price": 999.999
        }
      }
    ]
  }
}

批量插入

  • _bulk指定要批量插入
  • {"index":{}}:告诉ES这是索引插入操作

也可以指定文档ID比如{"index":{"_id":"002"}}

// 其他操作类型
{"create": {}}     // 插入(如果ID已存在则失败)
{"update": {}}     // 更新
{"delete": {}}     // 删除(只需要操作行,不需要数据行)
PUT /hotel/_bulk
{"index":{}}
{"name":"哈哈","city":"三亚","price":2412.34}
{"index":{}}
{"name":"哈asd哈","city":"2三亚","price":234412.3423}

条件删除

  • _delete_by_query:表示根据下面的条件进行删除文档
POST /hotel/_delete_by_query
{
    "query":{
        "term":{
            "city":{
                "value":"三亚"
            }
        }
    }
}
{
  "took": 31,
  "timed_out": false,
  "total": 1,
  "deleted": 1,
  "batches": 1,
  "version_conflicts": 0,
  "noops": 0,
  "retries": {
    "bulk": 0,
    "search": 0
  },
  "throttled_millis": 0,
  "requests_per_second": -1,
  "throttled_until_millis": 0,
  "failures": []
}

删除索引

DELETE hotel
{
  "acknowledged": true
}

Python API

安装包

uv add elasticsearch

基本API使用

连接

from elasticsearch import Elasticsearch
es = Elasticsearch("http://localhost:9200")

# 如果存在这个索引,先删除同时忽略掉404错误
es.indices.delete(index="py_index01",ingore=404)

创建索引

es.indices.create(index='py_index01',ignore=400)

插入数据

body = {
    "name":"tommy",
    "age" :20,
    "city":"shenzhen",
    "hobbies":"singing,dancing,reading"
}
es.index(index="py_index01",id=1,body=body)

查询

  • 全部查询
es.search(index="py_index01",query={"match_all":{}})
  • 普通查询
# q和q2写法都可以,不过如果关键词参数是body,只能是q完整的写法
q = {
    "term":{
        "name":{
            "value":"asd"
        }
    }
}
# 这里的关键词参数使用query之后,内部可以简略写法.
q2 = {
    "term":{
        "name":"asd"
    }
}
es.search(index="py_index01",query=q2)
  • 多词精确查询
query ={
    "terms":{
        "name":["asd","tomasdmy"]
    }
}
es.search(index="py_index01",query=query)
  • 范围查询
# 范围查询
"""
gt ,gte ,lt ,lte
"""
query = {
    "range":{
        "age":{
            "gt":10
        }
    }
}
es.search(index='py_index01',query=query)
  • exists/missing查询
# exists/missing

query = {
    "exists":{
        "field":"name"
    }
}

es.search(index="py_index01",query=query)
  • bool 过滤
# bool 过滤
"""
must:and
must_not : not
should:or
"""

query = {
    "bool":{
        "must":[
            {"term":{"name":"asd"},}
            {"term":{"age":22}}
        ]
    }
}
es.search(index="py_index01",query=query)
  • 多条件查询
"""
t1:name!=asd
t2:age 
t3:age=22
"""
query = {
    "bool":{
        "must":[
            {"term":{"name":"asd"}},
            {"term":{"Age":22}},
            {"exists":{"field":"age"}}
        ]
    }
}
es.search(index="py_index01",query=query)
  • multi_search
# multi_search,多个字段中分词查询
query = {
    "multi_match":{
        "query":"reading",
        "fields":["name","hobbies"]
    }
}
es.search(index='py_index01',query=query)
  • 通配符查询
# wildcard
query = {
    "wildcard":{
        "name":"a*"
    }
}

es.search(index="py_index01",query=query)
  • regexp
# regexp
query = {
    "regexp":{
        "name":".*mm.*"
    }
}

es.search(index='py_index01',query = query)
  • prefix
# prefix
query = {
    "prefix":{
        "name":"a"
    }
}
es.search(index='py_index01',query = query)
  • phrase_search
# phrass match
query = {
    "match_phrase":{
        "hobbies":"dancing"
    }
}
es.search(index='py_index01',query = query)

删除数据

  • id指定删除
# id 删除数据
es.delete(index='py_index01',id=1)
  • 条件删除
# delete_bu_query
query = {
    "match":{
        "name":"asd"
    }
}
es.delete_by_query(index="py_index01",query = query)

索引删除

es.indices.delete(index='py_index01')

向量操作

  • 批量插入操作

_index:要操作的索引

_source:要插入的数据

from elasticsearch import helpers

# actions = [
#     {"index": {"_index": "vector_index"}},
#     {"name": "苹果", "embedding": [0.2, 0.1, 0.4]},
#     {"index": {"_index": "vector_index"}},
#     {"name": "小船", "embedding": [0.7, 0.2, 0.6]},
#     {"index": {"_index": "vector_index"}},
#     {"name": "香蕉", "embedding": [0.3, 0.1, 0.3]},
# ]

actions = [
    {
        "_index":"vector_index",
        "_source":{
            "name":"苹果",
            "embedding":[0.2,0.1,0.4]
        }
    },
    {
        "_index":"vector_index",
        "_source":{
            "name":"小船",
            "embedding":[0.7,0.2,0.6]
        }
    },
    {
        "_index":"vector_index",
        "_source":{
            "name":"香蕉",
            "embedding":[0.3,0.1,0.3]
        }
    },
]
helpers.bulk(es,actions)
  • 查询所有记录
es.search(index='vector_index',body={"query":{"match_all":{}}})
  • 向量相似性计算

script_score:模板写法,通过脚本计算相似性

match_all:匹配所有文档,也可以使用前面的bool结合布尔查询,或term等进行特定类型搜索

script:下面是使用的脚本内容,其中source是脚本内容,params是参数.也可以对source使用""" """多行代码

# 向量相似性计算
temp = '橘子'
temp_emb = [0.2,0.2,0.4]

query = {
    "query" : {
        "script_score" : {
            "query":{
                "match_all":{}
            },
            "script":{
                "source":"cosineSimilarity(params.queryVector,'embedding') + 1.0",
                "params":{
                    "queryVector":temp_emb
                }
            }
        }
    }
}          

query2 = {
    "size": 2,  # 返回前10个最相似的结果
    "query": {
        "script_score": {
            "query": {"match_all": {}},
            "script": {
                "source": """
                    double sim = cosineSimilarity(params.queryVector, 'embedding');
                    return Math.max(0, sim);  // 或 sim + 1.0
                """,
                "params": {"queryVector": temp_emb}
            }
        }
    }
}  
response = es.search(index="vector_index",body=query2)

response['hits']['hits']
posted @ 2026-06-05 15:11  大胖熊哈  阅读(8)  评论(0)    收藏  举报