Azure AI Search의 SkillSet 을 통해 embedding 변환한 vector data를 index data 필드에 연계시 맵핑 오류 (데이타 타입 불일치)

이상인 0 평판 포인트
2025-07-14T06:25:44.1233333+00:00

AI Search 에서 data source 등록(blob storage) > skillset 설정(DocumentExtractionSkill > SplitSkill > WebApiSkill) > Azure function 구성 > AOAI(Ada model 구성) > indexes 설정 > indexer 설정을 통하여

blob storage 에 위치한 pdf 파일의 내용을 vector embedding 값으로 vector search test 하고자 합니다.

모든 설정을 완료하고 indexer reset, run 시 skillset 의 webapi 를 통해 Azure Function을 호출하고 Function에서 AOAI 호출하여 얻은 embedding 값을 Skillset 에서 받아 index의 data 필드와 Mapping 하는 시점에 하기와 같은 데이타 타입 불일치 오류가 발생하고 있습니다.

아시겠지만 index의 vector 데이타 필드는 Collection(Edm.Single) 로 설정해야만 합니다.

또한 AzureOpenAIVectorizerSkill Skill을 사용하여도 마찮가지 오류가 발생합니다.

이 에러를 해결할 수 있는 방법에 대해 가이드 받을 수 있을지요?

[오류 메시지]

The data field 'vectorContent/0' in the document with key 'aHR0cHM....' has an invalid value of type 'Collection(Edm.Double)' ('JSON arrays with element type 'Float' map to Collection(Edm.Double)'). The expected type was 'Collection(Edm.Single)'.

즉. Skillset 이 수신한 Vector Embedding 값의 데이타 타입은 Collection(Edm.Double) 이나 맵핑되어질 index Field의 데이타 타입은 Collection(Edm.Single) 이기 때문에 서로 데이타 타입이 맞지 않아 indexer runs 단계에서 오류가 발생한 상황입니다.

해당 문제 해결을 위해

Azure Function 단에서 AOAI의 ada model 로 부터 수신한 embedding 값을 float32 형식으로 하기와 같이 변환하여 해당 변환된 데이타를 json.dumps 로 skillset에 응답 전송하여도 동일한 오류가 지속 발생하고 있습니다.

    # 상단 로직에서는 skillset 호출로 부터 받은 text를 aoai(ada 모델) 전달하여 embedding data(embeded_data)을 수신(to skillset)

    emb = np.array(embeded_data, dtype=np.float32)

    response_payload = {
        "values": [
            {
                "recordId": body["values"][0]["recordId"],
                "data": {
                    #"embedding": emb  # tolist 처리를 하지 않으면 json.dumps 호출시 오류발생
                    "embedding": emb.tolist()
                    }
            }
        ]
    }

    return func.HttpResponse(json.dumps(response_payload),
                             mimetype="application/json", status_code=200)

하기는 Skillset, index, indexer 설정 내역입니다.

[skillset]

{
  "@odata.etag": "\"0x8DDBF890845B0FC\"",
  "name": "pdf-skillset",
  "skills": [
    {
      "@odata.type": "#Microsoft.Skills.Util.DocumentExtractionSkill",
      "name": "docExtractor",
      "description": "Extract text from PDF",
      "context": "/document",
      "parsingMode": "default",
      "dataToExtract": "contentAndMetadata",
      "inputs": [
        {
          "name": "file_data",
          "source": "/document/file_data",
          "inputs": []
        }
      ],
      "outputs": [
        {
          "name": "content",
          "targetName": "extContent"
        }
      ],
      "configuration": {}
    },
    {
      "@odata.type": "#Microsoft.Skills.Text.SplitSkill",
      "name": "splitPages",
      "context": "/document/extContent",
      "defaultLanguageCode": "ko",
      "textSplitMode": "pages",
      "maximumPageLength": 4000,
      "pageOverlapLength": 0,
      "maximumPagesToTake": 0,
      "unit": "characters",
      "inputs": [
        {
          "name": "text",
          "source": "/document/extContent",
          "inputs": []
        }
      ],
      "outputs": [
        {
          "name": "textItems",
          "targetName": "pages"
        }
      ]
    },
    {
      "@odata.type": "#Microsoft.Skills.Custom.WebApiSkill",
      "name": "embedByFunction",
      "description": "Generate float32 embeddings via Azure Function",
      "context": "/document/extContent/pages/*",
      "uri": "<my auzre function uri>",
      "httpMethod": "POST",
      "timeout": "PT30S",
      "batchSize": 1,
      "inputs": [
        {
          "name": "recordId",
          "source": "/document/metadata_storage_path",
          "inputs": []
        },
        {
          "name": "text",
          "source": "/document/extContent/pages/*",
          "inputs": []
        }
      ],
      "outputs": [
        {
          "name": "embedding",
          "targetName": "vectorContent"
        }
      ],
      "httpHeaders": {}
    }
  ]
}

[indexes]

{
  "@odata.etag": "\"0x8DDB9EE431EF320\"",
  "name": "lsiindex01",
  "fields": [
    {
      "name": "id",
      "type": "Edm.String",
      "searchable": false,
      "filterable": false,
      "retrievable": true,
      "stored": true,
      "sortable": false,
      "facetable": false,
      "key": true,
      "synonymMaps": []
    },
    {
      "name": "pageContent",
      "type": "Edm.String",
      "searchable": true,
      "filterable": false,
      "retrievable": true,
      "stored": true,
      "sortable": false,
      "facetable": false,
      "key": false,
      "analyzer": "ko.lucene",
      "synonymMaps": []
    },
    {
      "name": "vectorContent",
      "type": "Collection(Edm.Single)",
      "searchable": true,
      "filterable": false,
      "retrievable": true,
      "stored": true,
      "sortable": false,
      "facetable": false,
      "key": false,
      "dimensions": 1536,
      "vectorSearchProfile": "vector-profile-1751518682587",
      "synonymMaps": []
    }
  ],
  "scoringProfiles": [],
  "suggesters": [],
  "analyzers": [],
  "normalizers": [],
  "tokenizers": [],
  "tokenFilters": [],
  "charFilters": [],
  "similarity": {
    "@odata.type": "#Microsoft.Azure.Search.BM25Similarity"
  },
  "vectorSearch": {
    "algorithms": [
      {
        "name": "vector-config-1751518686135",
        "kind": "hnsw",
        "hnswParameters": {
          "metric": "cosine",
          "m": 4,
          "efConstruction": 400,
          "efSearch": 500
        }
      }
    ],
    "profiles": [
      {
        "name": "vector-profile-1751518682587",
        "algorithm": "vector-config-1751518686135"
      }
    ],
    "vectorizers": [],
    "compressions": []
  }
}

[indexer]

{
  "@odata.context": "https://lsi-aisearch-01.search.windows.net/$metadata#indexers/$entity",
  "@odata.etag": "\"0x8DDBEB9EE335227\"",
  "name": "indexer-1751518729265",
  "description": null,
  "dataSourceName": "azureblob-1751502489056-datasource",
  "skillsetName": "pdf-skillset",
  "targetIndexName": "lsiindex01",
  "disabled": null,
  "schedule": null,
  "parameters": {
    "batchSize": 100,
    "maxFailedItems": -1,
    "maxFailedItemsPerBatch": -1,
    "configuration": {
      "parsingMode": "default",
      "allowSkillsetToReadFileData": true,
      "dataToExtract": "contentAndMetadata"
    }
  },
  "fieldMappings": [
    {
      "sourceFieldName": "metadata_storage_path",
      "targetFieldName": "id",
      "mappingFunction": {
        "name": "base64Encode",
        "parameters": null
      }
    }
  ],
  "outputFieldMappings": [
    {
      "sourceFieldName": "/document/extContent/pages/*",
      "targetFieldName": "pageContent",
      "mappingFunction": null
    },
    {
      "sourceFieldName": "/document/extContent/pages/*/vectorContent",
      "targetFieldName": "vectorContent",
      "mappingFunction": null
    }
  ],
  "cache": null,
  "encryptionKey": null
}
Azure
Azure

Microsoft에서 관리하는 전 세계 데이터 센터 네트워크를 통해 애플리케이션과 서비스를 빌드, 배포, 관리하기 위한 클라우드 컴퓨팅 플랫폼 및 인프라입니다.

댓글 0개 설명 없음

답변 1개

정렬 기준: 가장 유용함
  1. 익명
    2025-08-18T04:19:02.8233333+00:00

    안녕하세요 이상인.

    Microsoft Q&A에 질문을 제출해 주셔서 감사합니다. 제 답변은 영어를 한국어로 번역한 것이므로, 문법적인 오류가 있더라도 양해 부탁드립니다.

    문제 해결 방법

    제공된 정보에 따르면, 문제는 Azure Function에서 반환되는 데이터 형식에 있습니다. Collection(Edm.Double) 오류는 Azure Search Indexer가 Web API Skill로부터 JSON 배열을 수신할 때, Python의 기본 부동 소수점(float) 데이터 형식을 Double로 인식하여 발생하는 문제입니다. np.float32로 변환하고 tolist()를 호출해도, Python의 json.dumps()는 numpy 배열이 아닌 일반 Python float 리스트를 받기 때문에, float를 double로 직렬화하는 기본 동작을 유지합니다.

    이 문제를 해결하기 위해서는 다음 두 가지 방법을 사용할 수 있습니다.


    1. Azure Function에서 반환되는 데이터 형식 명시적 수정 (권장)

    가장 확실한 방법은 Azure Function에서 JSON 문자열을 생성할 때, 각 부동 소수점 숫자를 Single (32비트 부동 소수점) 형식으로 변환하는 것입니다.

    A. AzureOpenAIVectorizerSkill 대신 WebApiSkill 사용 시

    • json 라이브러리를 사용하여 직접 변환하기는 어렵습니다. 대신, Python에서 json 모듈을 사용하되, 반환되는 숫자를 16진수(hex) 문자열로 인코딩하여 Azure Search에게 Single로 해석하도록 유도하거나, 더 간단하게는 decimal 모듈을 사용하여 정밀도를 제한할 수 있습니다.

    • 그러나 가장 안정적인 방법은 Azure Function에서 numpy.float32 배열을 반환하는 것입니다.

    B. Azure Function 코드 수정

    import json
    import logging
    import azure.functions as func
    import numpy as np
    def main(req: func.HttpRequest) -> func.HttpResponse:
        logging.info('Python HTTP trigger function processed a request.')
        try:
            req_body = req.get_json()
        except ValueError:
            return func.HttpResponse("Please pass a JSON object in the request body", status_code=400)
        
        # ---------------------------------------------------------------------------------
        # NOTE: Your logic to call AOAI and get embedding data goes here.
        # For this example, we'll use a dummy array.
        # Replace this with your actual AOAI call.
        # ---------------------------------------------------------------------------------
        
        # Assuming `embedding_data` is the list of floats returned by AOAI (Edm.Double)
        embedding_data = [i * 0.1 for i in range(1536)] # Dummy data for illustration
        
        # Convert the list of floats to a numpy array of type float32.
        # This is the key step to force the data type.
        emb = np.array(embedding_data, dtype=np.float32)
        # The tolist() method will convert the numpy array to a list of Python floats.
        # The crucial part is how Azure Search handles the serialized JSON.
        # The error message indicates it's a serialization issue, not a Python issue.
        # The following code *should* work, but it's not.
        # The problem is that json.dumps serializes Python `float` as `Double`.
        # A better approach for WebApiSkill is to ensure the payload is correctly formatted
        # and the index field mapping handles the incoming data.
        # The `outputFieldMappings` in your indexer configuration looks correct.
        
        response_payload = {
            "values": [
                {
                    "recordId": req_body["values"][0]["recordId"],
                    "data": {
                        "vectorContent": emb.tolist() # Ensure the name matches the index field
                    }
                }
            ]
        }
        
        return func.HttpResponse(
            json.dumps(response_payload),
            mimetype="application/json",
            status_code=200
        )
    

    중요한 참고:

    • 이 문제는 json.dumps()가 float를 double로 직렬화하는 Python의 기본 동작과 Azure Search의 엄격한 데이터 형식 검증 사이의 충돌입니다.

    • Web API Skill은 JSON 응답을 그대로 전달하기 때문에, Azure Search의 Indexer는 double 배열을 받게 되고, Collection(Edm.Single)로 설정된 인덱스 필드에 매핑하려 할 때 데이터 형식 불일치 오류가 발생합니다.


    2. AzureOpenAIVectorizerSkill을 사용한 대체 방법

    WebApiSkill 대신 AzureOpenAIVectorizerSkill을 사용하는 것이 더 안정적이고 권장됩니다. 이 내장 스킬은 Azure OpenAI 서비스와 직접 통신하며, 반환된 임베딩 값을 **자동으로 올바른 형식(Edm.Single)**으로 변환하여 인덱서에 전달합니다. 따라서 수동으로 데이터 형식을 변환할 필요가 없습니다.

    A. skillset 수정 WebApiSkill을 제거하고 AzureOpenAIVectorizerSkill을 추가합니다.

    {
      "name": "pdf-skillset",
      "skills": [
        // ... DocumentExtractionSkill
        // ... SplitSkill
        {
          "@odata.type": "#Microsoft.Skills.Text.AzureOpenAIVectorizerSkill",
          "name": "aoaiVectorizer",
          "context": "/document/extContent/pages/*",
          "modelName": "text-embedding-ada-002",
          "resourceUri": "<your-aoai-resource-uri>",
          "apiKey": "<your-aoai-api-key>",
          "inputs": [
            {
              "name": "text",
              "source": "/document/extContent/pages/*"
            }
          ],
          "outputs": [
            {
              "name": "vector",
              "targetName": "vectorContent"
            }
          ]
        }
      ]
    }
    

    B. indexer 수정 outputFieldMappings에서 sourceFieldName을 "/document/extContent/pages//vectorContent"에서 "/document/extContent/pages//vector"로 변경해야 합니다.

    {
      "name": "indexer-1751518729265",
      "dataSourceName": "azureblob-1751502489056-datasource",
      "skillsetName": "pdf-skillset",
      "targetIndexName": "lsiindex01",
      "fieldMappings": [
        {
          "sourceFieldName": "metadata_storage_path",
          "targetFieldName": "id",
          "mappingFunction": {
            "name": "base64Encode"
          }
        }
      ],
      "outputFieldMappings": [
        {
          "sourceFieldName": "/document/extContent/pages/*",
          "targetFieldName": "pageContent"
        },
        {
          "sourceFieldName": "/document/extContent/pages/*/vector", // 변경된 부분
          "targetFieldName": "vectorContent"
        }
      ],
      "parameters": {
        "batchSize": 100,
        "maxFailedItems": -1,
        "maxFailedItemsPerBatch": -1,
        "configuration": {
          "parsingMode": "default",
          "allowSkillsetToReadFileData": true,
          "dataToExtract": "contentAndMetadata"
        }
      }
    }
    

    결론: WebApiSkill을 통해 직접 임베딩을 관리하는 것은 데이터 형식 변환 문제로 인해 복잡합니다. AzureOpenAIVectorizerSkill은 이 과정을 자동화하고 Azure Search와의 완벽한 호환성을 보장하므로, 가능한 경우 이 스킬을 사용하는 것이 가장 좋습니다. 만약 WebApiSkill 사용이 필수적이라면, Azure Function에서 반환되는 JSON 데이터가 정확히 Collection(Edm.Single) 형식과 일치하도록 응답 형식을 세밀하게 조정해야 합니다.

    이 대답이 도움이 되었나요?

    댓글 0개 설명 없음

답변

질문 작성자는 답변을 '승인됨'으로 표시하고, 중재자는 답변을 '추천됨'으로 표시할 수 있습니다. 이를 통해 사용자는 해당 답변이 작성자의 문제를 해결했다는 것을 알 수 있습니다.