LoginSignup
0
1

Azure AI Search のインデックスを Python と JSON 定義ファイルで作成する

Posted at

Python スクリプトからインデックスを作成しようとしたときに、Azure AI Search の Python SDK を使う方法だとちょっと面倒そうだったので、SDK を使わずに (Azure Portal から入手できる) JSON 形式のインデックス定義ファイルを REST API に投げつける方式でやってみたのでメモ。1

from os import getenv
import urllib.request

SEARCH_RESOURCE = getenv("SEARCH_RESOURCE")
SEARCH_API_KEY = getenv("SEARCH_API_KEY")
SEARCH_API_VERSION = getenv("SEARCH_API_VERSION", "2023-11-01")


def create_index_from_json(index: str) -> bytes:
    """Azure AI Search のインデックス定義 (JSON 文字列) からインデックスを作成する"""
    url = f"https://{SEARCH_RESOURCE}.search.windows.net/indexes?api-version={SEARCH_API_VERSION}"
    data = index
    headers = {
        "Content-Type": "application/json",
        "api-key": SEARCH_API_KEY
    }
    try:
        request = urllib.request.Request(url, data, headers)
        with urllib.request.urlopen(request) as response:
            return response.read()
    except urllib.error.HTTPError as err:
        return err.fp.read()
with open("index.json", "rt") as f:
    result = create_index_from_json(f.read())

print(result.decode())

参考: 検索インデックスの作成 - Azure AI Search | Microsoft Learn

  1. 「それだけなら curl コマンドとかでいいじゃん」というツッコミがありそうだが、実際にやりたかったのは「インデックス定義を少しいじりつつ複数のインデックスを作成する」だったので、Python から扱えることに意味はあった。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1