MST

星途 面试题库

面试题:ElasticSearch搜索API在复杂业务场景的应用

假设存在一个电商搜索场景,用户可以根据商品名称、描述、价格范围、销量范围、品牌等多个条件进行搜索,并且搜索结果需要按照相关性、销量、价格等多维度进行灵活排序。请详细说明如何使用ElasticSearch搜索API来设计和实现这样的复杂搜索功能,包括索引结构设计、查询语句构建以及排序策略的实现思路。
43.0万 热度难度
数据库ElasticSearch

知识考点

AI 面试

面试题答案

一键面试

索引结构设计

  1. 商品名称:使用 text 类型,并配置合适的分析器,如 ik_max_word(针对中文),以支持分词搜索。例如:
{
  "mappings": {
    "properties": {
      "product_name": {
        "type": "text",
        "analyzer": "ik_max_word"
      }
    }
  }
}
  1. 商品描述:同样使用 text 类型和合适分析器,以支持更详细的文本搜索。
{
  "mappings": {
    "properties": {
      "product_description": {
        "type": "text",
        "analyzer": "ik_max_word"
      }
    }
  }
}
  1. 价格:使用 floatinteger 类型(根据价格精度),用于范围查询和排序。
{
  "mappings": {
    "properties": {
      "price": {
        "type": "float"
      }
    }
  }
}
  1. 销量:使用 integer 类型,用于范围查询和排序。
{
  "mappings": {
    "properties": {
      "sales": {
        "type": "integer"
      }
    }
  }
}
  1. 品牌:使用 keyword 类型,用于精确匹配。
{
  "mappings": {
    "properties": {
      "brand": {
        "type": "keyword"
      }
    }
  }
}

查询语句构建

  1. 多条件查询:使用 bool 查询来组合不同条件。例如,查询商品名称包含 "手机",价格在 1000 到 5000 之间,品牌为 "华为" 的商品:
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "product_name": "手机"
          }
        },
        {
          "range": {
            "price": {
              "gte": 1000,
              "lte": 5000
            }
          }
        },
        {
          "term": {
            "brand": "华为"
          }
        }
      ]
    }
  }
}
  1. 模糊查询:如果需要对商品描述进行模糊搜索,可以使用 fuzzy 查询。例如,模糊查询描述中包含 "智能" 的商品:
{
  "query": {
    "fuzzy": {
      "product_description": {
        "value": "智能",
        "fuzziness": "AUTO"
      }
    }
  }
}

排序策略实现思路

  1. 相关性排序:默认情况下,ElasticSearch 会根据文档与查询条件的相关性进行排序。可以通过调整 match 查询中的 boost 参数来调整某些字段在相关性计算中的权重。例如,提高商品名称在相关性中的权重:
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "product_name": {
              "query": "手机",
              "boost": 2
            }
          }
        },
        {
          "match": {
            "product_description": "手机"
          }
        }
      ]
    }
  }
}
  1. 销量排序:使用 sort 参数,按照销量降序排列:
{
  "query": {
    "match_all": {}
  },
  "sort": [
    {
      "sales": {
        "order": "desc"
      }
    }
  ]
}
  1. 价格排序:同样使用 sort 参数,按照价格升序排列:
{
  "query": {
    "match_all": {}
  },
  "sort": [
    {
      "price": {
        "order": "asc"
      }
    }
  ]
}
  1. 多维度排序:可以组合多个排序字段,例如先按销量降序,再按价格升序:
{
  "query": {
    "match_all": {}
  },
  "sort": [
    {
      "sales": {
        "order": "desc"
      }
    },
    {
      "price": {
        "order": "asc"
      }
    }
  ]
}