返回

Elasticsearch基本语法和实战解析,瞬间化繁为简!

后端

随着公司业务的发展,MySQL已经无法满足大数据量的业务场景,因此,很多公司会把数据迁移到Elasticsearch中。

作为一名合格的程序员,掌握Elasticsearch的基本语法是必备的技能。因此,今天我将重点介绍Elasticsearch的基本语法,包括索引、文档、字段、类型、查询、聚合和分面。

通过本文,你将能够快速掌握Elasticsearch的基本用法,并能够轻松地构建搜索应用程序。

1. 索引

索引是Elasticsearch中存储数据的基本单位。一个索引可以包含一个或多个类型。

要创建索引,可以使用以下命令:

PUT /my-index

2. 文档

文档是Elasticsearch中存储数据的基本单元。一个文档可以包含一个或多个字段。

要创建文档,可以使用以下命令:

POST /my-index/my-type/_doc

其中,my-index是索引名称,my-type是类型名称,_doc是文档ID。

3. 字段

字段是Elasticsearch中存储数据的最小单位。一个字段可以是字符串、数字、日期、布尔值等。

要创建字段,可以在创建索引时指定字段类型。例如:

PUT /my-index
{
  "mappings": {
    "my-type": {
      "properties": {
        "name": {
          "type": "text"
        },
        "age": {
          "type": "integer"
        },
        "date": {
          "type": "date"
        }
      }
    }
  }
}

4. 类型

类型是Elasticsearch中对文档进行分类的一种方式。一个索引可以包含一个或多个类型。

要创建类型,可以在创建索引时指定类型名称。例如:

PUT /my-index
{
  "mappings": {
    "my-type1": {
      "properties": {
        "name": {
          "type": "text"
        },
        "age": {
          "type": "integer"
        },
        "date": {
          "type": "date"
        }
      }
    },
    "my-type2": {
      "properties": {
        "name": {
          "type": "text"
        },
        "address": {
          "type": "text"
        },
        "phone": {
          "type": "text"
        }
      }
    }
  }
}

5. 查询

查询是Elasticsearch中检索数据的基本操作。Elasticsearch提供了多种查询方式,包括:

  • term query: 用于精确匹配字段值。
  • match query: 用于模糊匹配字段值。
  • range query: 用于匹配字段值范围。
  • wildcard query: 用于匹配通配符字段值。
  • bool query: 用于组合多个查询条件。

要进行查询,可以使用以下命令:

GET /my-index/my-type/_search
{
  "query": {
    "match": {
      "name": "John Doe"
    }
  }
}

6. 聚合

聚合是Elasticsearch中对查询结果进行统计分析的操作。Elasticsearch提供了多种聚合方式,包括:

  • sum aggregation: 用于计算字段值的总和。
  • avg aggregation: 用于计算字段值的平均值。
  • min aggregation: 用于计算字段值的最小值。
  • max aggregation: 用于计算字段值的最大值。
  • cardinality aggregation: 用于计算字段值的基数。

要进行聚合,可以使用以下命令:

GET /my-index/my-type/_search
{
  "aggregations": {
    "age_stats": {
      "stats": {
        "field": "age"
      }
    }
  }
}

7. 分面

分面是Elasticsearch中对查询结果进行分组的操作。Elasticsearch提供了多种分面方式,包括:

  • terms facet: 用于对字段值进行分组。
  • range facet: 用于对字段值范围进行分组。
  • date histogram facet: 用于对字段值日期进行分组。

要进行分面,可以使用以下命令:

GET /my-index/my-type/_search
{
  "facets": {
    "age_facet": {
      "terms": {
        "field": "age"
      }
    }
  }
}

8. 结语

Elasticsearch是一个非常强大的搜索引擎,掌握了它的基本语法,就可以快速构建搜索应用程序。本文只是介绍了Elasticsearch的基本语法,还有很多高级特性没有介绍。如果您想了解更多关于Elasticsearch的内容,可以参考官方文档。