Elasticsearch搜索引擎实战应用


Elasticsearch搜索引擎实战应用

Elasticsearch是目前最流行的全文搜索引擎,它基于Lucene构建,提供了强大的全文搜索、结构化搜索和分析能力。本文将介绍Elasticsearch的核心概念和实战应用技巧。

一、索引设计

// 创建索引
PUT /products
{
  "settings": {
    "number_of_shards": 3,
    "number_of_replicas": 1,
    "analysis": {
      "analyzer": {
        "ik_smart_analyzer": {
          "type": "custom",
          "tokenizer": "ik_max_word",
          "filter": ["lowercase"]
        }
      }
    }
  },
  "mappings": {
    "properties": {
      "name": {
        "type": "text",
        "analyzer": "ik_max_word",
        "search_analyzer": "ik_smart"
      },
      "description": {
        "type": "text",
        "analyzer": "ik_max_word"
      },
      "price": { "type": "double" },
      "category": { "type": "keyword" },
      "tags": { "type": "keyword" },
      "created_at": { "type": "date" },
      "suggest": {
        "type": "completion"
      }
    }
  }
}

二、搜索查询

// 全文搜索
GET /products/_search
{
  "query": {
    "multi_match": {
      "query": "笔记本电脑",
      "fields": ["name^3", "description"],
      "type": "best_fields"
    }
  },
  "highlight": {
    "fields": {
      "name": {},
      "description": {}
    }
  }
}

// 组合查询
GET /products/_search
{
  "query": {
    "bool": {
      "must": [
        { "match": { "name": "手机" } }
      ],
      "filter": [
        { "range": { "price": { "gte": 1000, "lte": 5000 } } },
        { "term": { "category": "electronics" } },
        { "terms": { "tags": ["5G", "旗舰"] } }
      ],
      "should": [
        { "term": { "tags": { "value": "新品", "boost": 2 } } }
      ]
    }
  },
  "sort": [
    { "_score": { "order": "desc" } },
    { "price": { "order": "asc" } }
  ]
}

三、聚合分析

// 分类聚合 + 统计
GET /products/_search
{
  "size": 0,
  "aggs": {
    "by_category": {
      "terms": { "field": "category", "size": 20 },
      "aggs": {
        "avg_price": { "avg": { "field": "price" } },
        "max_price": { "max": { "field": "price" } },
        "min_price": { "min": { "field": "price" } }
      }
    },
    "price_ranges": {
      "range": {
        "field": "price",
        "ranges": [
          { "key": "低价", "to": 100 },
          { "key": "中价", "from": 100, "to": 1000 },
          { "key": "高价", "from": 1000 }
        ]
      }
    }
  }
}

四、搜索建议

// 自动补全
GET /products/_search
{
  "suggest": {
    "product_suggest": {
      "prefix": "笔记本",
      "completion": {
        "field": "suggest",
        "size": 10,
        "skip_duplicates": true
      }
    }
  }
}

// 拼音搜索 - 需要安装pinyin分词器
// 同义词搜索
PUT /products/_settings
{
  "index": {
    "analysis": {
      "filter": {
        "synonym_filter": {
          "type": "synonym",
          "synonyms": ["手机,智能手机,cellphone"]
        }
      }
    }
  }
}

Elasticsearch是构建搜索功能的强大工具,但也要注意合理设计索引、避免深度分页、控制聚合数量等性能陷阱。建议从简单查询开始,逐步掌握复合查询和聚合分析,最终构建出满足业务需求的搜索系统。


0.064934s