首页 > 编程问答 >无法使用适用于 Azure AI 搜索的 Python SDK 将数据添加到 ComplexField

无法使用适用于 Azure AI 搜索的 Python SDK 将数据添加到 ComplexField

时间:2024-07-25 12:18:52浏览次数:10  
标签:python azure indexing azure-cognitive-search

我想将带有嵌套字典的有效负载上传到 Azure AI 搜索索引。我在索引中使用 ComplexField 作为负载中的嵌套字典。索引无法识别嵌套字典,并且出现空错误。这是我的代码:

    ComplexField,
    CorsOptions,
    SearchIndex,
    ScoringProfile,
    SearchFieldDataType,
    SimpleField,
    SearchableField,
)

request_example = {
        
            "id": "1",
            "text": "bla",
            "payload": {
                "processId": "00665",
                "color": "green"
            }
        
    }

# Create a search index  
index_client = SearchIndexClient(endpoint=service_endpoint, credential=credential)  
fields = [  
    SimpleField(name="id", type=SearchFieldDataType.String, key=True, sortable=True, filterable=True, facetable=True),  
    SearchableField(name="text", type=SearchFieldDataType.String),  
    ComplexField(
        name="payload",
        fields=[
            SimpleField(name="processId", type=SearchFieldDataType.String),
            SimpleField(name="color", type=SearchFieldDataType.String),
        ],
        collection=True,
    )
]  
  
# Configure the vector search configuration  
vector_search = VectorSearch(  
    algorithms=[  
        HnswAlgorithmConfiguration(  
            name="myHnsw",  
            kind=VectorSearchAlgorithmKind.HNSW,  
            parameters=HnswParameters(  
                m=4,  
                ef_construction=400,  
                ef_search=500,  
                metric=VectorSearchAlgorithmMetric.COSINE,  
            )  
        ),  
    ],  
    profiles=[  
        VectorSearchProfile(  
            name="myHnswProfile",  
            algorithm_configuration_name="myHnsw",   
        ),  
    ],  
)  
  
semantic_config = SemanticConfiguration(  
    name="my-semantic-config",  
    prioritized_fields=SemanticPrioritizedFields(  
        # title_field=SemanticField(field_name="title"),  
        # keywords_fields=[SemanticField(field_name="color")],  
        content_fields=[SemanticField(field_name="text")]  
    )  
)  
  
# Create the semantic settings with the configuration  
semantic_search = SemanticSearch(configurations=[semantic_config])  
cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60)
from typing import List
scoring_profiles: List[ScoringProfile] = []
# Create the search index with the semantic settings  
index = SearchIndex(name="complex_field_test", fields=fields,  
                    vector_search=vector_search, semantic_search=semantic_search,scoring_profiles=scoring_profiles, cors_options=cors_options)  
result = index_client.create_or_update_index(index)  
print(f'{result.name} created')  

# Upload some documents to the index
search_client = SearchClient(endpoint=service_endpoint, index_name="complex_field_test", credential=credential)
result = search_client.upload_documents([request_example])  
print(f"Uploaded {len(documents)} documents")

我得到的错误:

The request is invalid. Details: A null value was found for the property named 'payload', which has the expected type 'Collection(search.complex.payload)[Nullable=False]'. The expected type 'Collection(search.complex.payload)[Nullable=False]' does not allow null values.

因此,据我了解,嵌套字典“有效负载”未被识别并且显示为空,尽管子字段已在索引中注册并且没有空值。你能帮我解决这个问题吗?如何向 ComplexField 添加数据?


在使用 Azure AI 搜索的 Python SDK 时遇到的错误信息表明,的索引定义预期“payload”字段是一个复杂类型数组 (Collection(search.complex.payload)),但它收到的值是单个对象。

为了解决这个问题,需要将“payload”的值包装在一个列表中,即使它只有一个元素:

request_example = {
    "id": "1",
    "text": "bla",
    "payload": [  # Wrap the payload object in a list
        {
            "processId": "00665",
            "color": "green"
        }
    ]
}

通过将“payload”的值包装在一个列表中,告诉 Azure AI 搜索这是一个复杂类型数组,这与的索引定义相匹配。

另外,请确保的 ComplexField 定义中 collection=True 已经设置。这将确保该字段可以接受多个复杂对象。

以下是更正后的代码片段:

# ... other code ...

# Upload some documents to the index
search_client = SearchClient(endpoint=service_endpoint, index_name="complex_field_test", credential=credential)
result = search_client.upload_documents([request_example])  # "payload" is now a list
print(f"Uploaded {len(result)} documents") 

通过进行此更改,应该能够成功将数据上传到包含 ComplexField 的 Azure AI 搜索索引。

标签:python,azure,indexing,azure-cognitive-search
From: 77702579

相关文章

  • 为什么上传文件时我的 Azure 函数应用 blob 触发器不起作用?
    我用python创建了一个blob触发函数应用程序。我的存储帐户中还有一个Blob存储。设置(local.settings,function.json)似乎没问题。运行:funcstart并在blob中上传文件后,没有任何反应。这是代码:importloggingfromazure.functionsimportInputStreamimportpand......
  • 如何使用 Python 从 Square 中的创建客户方法中检索客户 ID
    我正在square创建一个客户并得到如下结果。我需要的是获取客户的id。我的代码:fromsquare.clientimportClientclient=Client(access_token=settings.SQUARE_ACCESS_TOKEN,environment=settings.SQUARE_ENVIRONMENT,)api_customers=client.customers......
  • 为什么从.导入Python
    我使用的存储库的结构如下:在myrepo/src/中有:主要.pycore.py和somepkgsomepkg有init.py和其他python文件。somepkg不是任何文件中的类或函数。在main.py中,我看到:from.importcorefrom.importsomepkg我的问题是from和.......
  • 使用 Python 中的 Square API 检索客户 ID
    我正在为Square开发一个客户创建表单,它将创建一个客户,然后立即检索他们的ID以在程序中进一步使用。但是,我不知道如何使用API来过滤使用list_customers命令返回的数据。我找到了这篇文章:HowtoretrievecustomeridfromcreatecustomermethodinSquareusing......
  • 如何通过在字符串中使用 \u 或 \U 转义来正确表示 python3 (3.6.1+) 中的补充 unico
    最近我正在学习python,在python3中遇到了unicode转义文字的问题。似乎像Java一样,\u转义被解释为Java使用的UTF-16代码点,但问题来了:例如,如果我尝试放置3个字节的utf-8字符,例如“♬”(https://unicode-table.com/en/266C/),甚至是补充unicode字符,例如“......
  • 我的 Python 代码和 Cycle Time 小部件之间的平均周期时间不同
    我过去遇到过如何在周期时间小部件中计算平均周期时间的一些问题,因此我决定使用Python进行分析,看看是否找到任何方法来计算平均周期时间并获得相同的结果周期时间小部件中显示的值。我的问题是我无法达到周期时间小部件中显示的相同的平均周期时间值。你们能帮我解决这......
  • python3之requests库使用
    使用https://www.cnblogs.com/caroline2016/p/17007956.html建立的api测试下requests库怎么使用。模拟登录时laravelapi那边出现了 Sessionstorenotsetonrequest.错误。解决办法在app/Http/Kernel.php中api中间件组中添加两行代码:<?phpprotected$middlewareGrou......
  • 如何利用Python中的pyecharts制作—不同的柱状图
    目录专栏导读库的介绍库的安装1、柱状图(防止x轴标签名过长)2、柱状图—堆叠样式3、复合型柱状图4、柱状图—字典型总结专栏导读......
  • 六、【Python】基础教程-【Python全掌握】六大基础数据类型:浮点、布尔、列表、元组、
    ......
  • 用于获取半径内邮政编码的 Python 脚本无法正确填充 CSV
    我正在尝试编写一个Python脚本,该脚本读取包含邮政编码的CSV文件,使用API获取半径内的邮政编码,然后将结果填充到CSV中的新列中。API请求似乎工作正常,我可以在控制台输出中看到响应。但是,生成的CSV文件在radius_zips列中没有预期的值。这是我当前的脚本:......