给出 RESTful 搜索 API 的 Swagger 定义

解读

面试官把“写 Swagger”当成一道综合过滤器:既考你对 Lucene 索引模型的理解,又考你能否把倒排索引、分词、相关性评分这些底层概念无损地映射成 REST 资源。国内大厂普遍要求“能写能落地”,所以 Swagger 必须可直接导入 Swagger-UI 生成在线文档,字段、响应码、示例都要对标生产环境。切忌只写“200 返回 JSON”这种学生级答案。

知识点

  1. REST 资源设计:把“索引”当资源 /indices/{indexName},把“搜索”当子资源 /indices/{indexName}/search,符合国内阿里/腾讯/字节对内接口规范。
  2. Lucene 查询 DSL 子集:必须覆盖 TermQuery、BooleanQuery、RangeQuery、PhraseQuery、FuzzyQuery,且字段类型与 Lucene 完全一致(text/string/long/double/geo)。
  3. 高阶参数:
    • track_total_hits(默认 10 000,兼容 ES 7.x 行为)
    • min_score 过滤低分文档
    • profile 返回 Lucene 的 Explanation,方便调优
  4. 响应结构:
    • took 是 Lucene 的 IndexSearcher.search 耗时,单位 ms
    • hits._score 必须返回 float,且保留 6 位小数,避免前端精度丢失
  5. 错误码:
    • 400 查询语法错误,返回 Lucene ParseException 原文
    • 422 字段映射冲突,提示 “field [xxx] is not indexed”
  6. Swagger 语法:
    • 使用 OpenAPI 3.0.3(国内云厂商网关统一版本)
    • components.schemas 必须声明 x-java-class 扩展,方便 Swagger-Codegen 直接生成 Lucene Query 子类
    • example 字段给出中文+英文双示例,体现国际化能力

答案

openapi: 3.0.3
info:
  title: Lucene Search API
  version: 1.0.0
  description: 纯 Lucene 原生 REST 服务,无 Elasticsearch 依赖
servers:
  - url: http://lucene-gateway.company.com:8080
paths:
  /indices/{indexName}/search:
    post:
      summary: 在指定索引上执行 Lucene 查询
      operationId: search
      tags: [Search]
      parameters:
        - name: indexName
          in: path
          required: true
          schema:
            type: string
            pattern: '^[a-z0-9-_]+$'
          example: ecommerce_product_v2
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/SearchRequest'
            example:
              query:
                bool:
                  must:
                    - term: { brand: "小米" }
                  filter:
                    - range: { price: { gte: 1000, lte: 5000 } }
              from: 0
              size: 10
              track_total_hits: true
              sort: [{ price: { order: desc } }]
              highlight:
                fields: { title: { fragment_size: 150 } }
      responses:
        '200':
          description: 查询成功
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SearchResponse'
        '400':
          description: 查询语法错误
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              example:
                code: 400
                message: "Cannot parse '+(title:小米 price:>abc)': Encountered 'abc' at line 1, column 18."
        '422':
          description: 字段未索引或类型不匹配
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              example:
                code: 422
                message: "field [price] is not indexed"
components:
  schemas:
    SearchRequest:
      type: object
      required: [query]
      properties:
        query:
          $ref: '#/components/schemas/QueryContainer'
        from:
          type: integer
          minimum: 0
          default: 0
        size:
          type: integer
          minimum: 1
          maximum: 1000
          default: 10
        track_total_hits:
          type: boolean
          default: false
        min_score:
          type: number
          format: float
        sort:
          type: array
          items:
            type: object
            additionalProperties:
              type: object
              properties:
                order:
                  enum: [asc, desc]
        highlight:
          type: object
          properties:
            fields:
              type: object
              additionalProperties:
                type: object
                properties:
                  fragment_size:
                    type: integer
                    default: 100
    QueryContainer:
      type: object
      minProperties: 1
      maxProperties: 1
      additionalProperties: false
      properties:
        term:
          $ref: '#/components/schemas/TermQuery'
        terms:
          $ref: '#/components/schemas/TermsQuery'
        range:
          $ref: '#/components/schemas/RangeQuery'
        bool:
          $ref: '#/components/schemas/BoolQuery'
        match:
          $ref: '#/components/schemas/MatchQuery'
        match_phrase:
          $ref: '#/components/schemas/MatchPhraseQuery'
        fuzzy:
          $ref: '#/components/schemas/FuzzyQuery'
    TermQuery:
      type: object
      additionalProperties:
        type: string
      example: { brand: "小米" }
    TermsQuery:
      type: object
      additionalProperties:
        type: array
        items: { type: string }
      example: { status: ["instock", "shipping"] }
    RangeQuery:
      type: object
      additionalProperties:
        type: object
        properties:
          gte: {}
          lte: {}
          gt: {}
          lt: {}
          format:
            type: string
            default: "yyyy-MM-dd HH:mm:ss"
      example: { price: { gte: 1000, lte: 5000 }, createTime: { gte: "2023-01-01 00:00:00" } }
    BoolQuery:
      type: object
      properties:
        must:
          type: array
          items: { $ref: '#/components/schemas/QueryContainer' }
        should:
          type: array
          items: { $ref: '#/components/schemas/QueryContainer' }
        must_not:
          type: array
          items: { $ref: '#/components/schemas/QueryContainer' }
        filter:
          type: array
          items: { $ref: '#/components/schemas/QueryContainer' }
        minimum_should_match:
          type: integer
          minimum: 1
    MatchQuery:
      type: object
      additionalProperties:
        type: object
        properties:
          query: { type: string }
          analyzer: { type: string }
          operator: { enum: [or, and] }
          boost: { type: number, format: float }
      example: { title: { query: "红米手机", analyzer: "ik_max_word", operator: "and" } }
    MatchPhraseQuery:
      type: object
      additionalProperties:
        type: object
        properties:
          query: { type: string }
          slop: { type: integer, default: 0 }
      example: { title: { query: "红米手机", slop: 1 } }
    FuzzyQuery:
      type: object
      additionalProperties:
        type: object
        properties:
          value: { type: string }
          fuzziness: { type: string, default: "AUTO" }
          max_expansions: { type: integer, default: 50 }
      example: { brand: { value: "xioami", fuzziness: "2" } }
    SearchResponse:
      type: object
      properties:
        took:
          type: integer
          description: Lucene 搜索耗时,单位 ms
        timed_out:
          type: boolean
          default: false
        _shards:
          type: object
          properties:
            total: { type: integer }
            successful: { type: integer }
            skipped: { type: integer }
            failed: { type: integer }
        hits:
          type: object
          properties:
            total:
              type: object
              properties:
                value: { type: integer }
                relation: { enum: [eq, gte] }
            max_score: { type: number, format: float }
            hits:
              type: array
              items:
                type: object
                properties:
                  _index: { type: string }
                  _id: { type: string }
                  _score: { type: number, format: float }
                  _source: { type: object }
                  highlight:
                    type: object
                    additionalProperties:
                      type: array
                      items: { type: string }
      example:
        took: 12
        timed_out: false
        _shards: { total: 5, successful: 5, skipped: 0, failed: 0 }
        hits:
          total: { value: 1024, relation: "gte" }
          max_score: 12.345678
          hits:
            - _index: "ecommerce_product_v2"
              _id: "P123456"
              _score: 12.345678
              _source: { title: "Redmi Note 12", brand: "小米", price: 1299 }
              highlight: { title: ["<em>Redmi</em> Note 12"] }
    Error:
      type: object
      properties:
        code: { type: integer }
        message: { type: string }

拓展思考

  1. 性能陷阱:
    如果面试官追问“十万 QPS 怎么压测”,可答:

    • 在 Swagger 的 x-extensions 里加 “x-rate-limit”: 10000,网关层直接限流;
    • /search 接口支持 request_cache=true,利用 Lucene LRU queryCache,命中率>90%。
  2. 安全加固:
    国内等保 2.0 要求查询字段白名单,可在 Swagger 里加 “x-field-allowlist”: ["title", "brand", "price"],网关层结合 OPA 做实时校验。

  3. 版本演进:
    当 Lucene 升级 10.x 后,knn 向量检索成为一等公民,只需在 QueryContainer 新增 “knn” 字段,无需改路径,保持 REST 资源稳定,体现向前兼容设计。