You need to enable JavaScript to run this app. 如何将指定ElasticSearch JSON查询转换为FastAPI可用的Pydantic Schema
优惠活动
大模型
产品
解决方案
定价
更多

如何将指定ElasticSearch JSON查询转换为FastAPI可用的Pydantic Schema

ElasticSearch DSL转FastAPI Pydantic模型方案

1. 分层定义Pydantic模型

完全对齐ES DSL的层级结构定义模型,保证导出的结构和原生查询100%一致:

from pydantic import BaseModel
from typing import List, Union, Dict

# 内层range查询的参数结构
class RangeCondition(BaseModel):
    gte: int | float
    lte: int | float

# 内层multi_match查询的参数结构
class MultiMatch(BaseModel):
    query: str
    fields: List[str]

# must数组中子查询的包装结构
class MultiMatchWrapper(BaseModel):
    multi_match: MultiMatch

class RangeWrapper(BaseModel):
    range: Dict[str, RangeCondition]

# bool查询结构
class BoolQuery(BaseModel):
    must: List[Union[MultiMatchWrapper, RangeWrapper]]

# 第二层query字段结构
class ESQueryInner(BaseModel):
    bool: BoolQuery

# 最顶层ES DSL结构
class ESQuery(BaseModel):
    query: ESQueryInner

2. 生成查询验证结构

按以下方式实例化模型,导出的字典可直接传给ES客户端:

# 构造你需要的查询条件
query = ESQuery(
    query=ESQueryInner(
        bool=BoolQuery(
            must=[
                MultiMatchWrapper(multi_match=MultiMatch(query="JOHN AND ANDY", fields=["FIRST_NAME"])),
                MultiMatchWrapper(multi_match=MultiMatch(query="SAM", fields=["LAST_NAME"])),
                RangeWrapper(range={"height": RangeCondition(gte=0, lte=100)}),
                RangeWrapper(range={"length1": RangeCondition(gte=0, lte=100)}),
                RangeWrapper(range={"length2": RangeCondition(gte=0, lte=100)}),
                RangeWrapper(range={"length3": RangeCondition(gte=0, lte=100)}),
                RangeWrapper(range={"length4": RangeCondition(gte=0, lte=100)}),
            ]
        )
    )
)

# 转成ES可识别的字典结构
es_dsl = query.model_dump()

3. FastAPI接口使用示例

from fastapi import FastAPI
from elasticsearch import AsyncElasticsearch

app = FastAPI()
# 初始化ES客户端
es = AsyncElasticsearch("http://你的ES服务地址:9200")

@app.post("/es-search")
async def es_search(query: ESQuery, index_name: str):
    # 直接传入模型导出的DSL即可
    result = await es.search(index=index_name, body=query.model_dump())
    return result

说明

  • 模型支持任意字段的range查询,新增字段无需修改模型,直接在RangeWrapper的range参数中传入字段名即可
  • 所有字段会自动做类型校验,传入非法参数会在FastAPI层直接返回错误,不会传到ES导致查询失败

内容的提问来源于stack exchange,提问作者Chaman17

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 14:36:05