iOSエンジニアのつぶやき

毎朝8:30に iOS 関連の技術について1つぶやいています。まれに釣りについてつぶやく可能性があります。

【Algolia】特定の属性のみを検索対象とした検索

今回は Algolia で、特定の属性のみをクエリの対象とした検索機能の実装を行ったので、その方法を簡単に紹介したいと思います🏃🏻‍♂️

それではやっていく

ということで、Query.restrictSearchableAttributes として属性を設定することで、特定の属性を対象として検索を行います。.restrictSearchableAttributes についてはドキュメンとでも解説されているので、ぜひ覗いて見てください。

https://www.algolia.com/doc/api-reference/api-parameters/restrictSearchableAttributes/?language=swift

    private let client = SearchClient(appID: "YOUR_APP_ID", apiKey: "YOUR_API_KEY")

    func search(with fieldId: String, page: Int, perPage: Int) {
        let query = Query(fieldId).set(\.restrictSearchableAttributes, to: ["fieldId"])

        client.index(withName: "guides").search(query: query.set(\.hitsPerPage, to: perPage).set(\.page, to: page)) { result in
            switch result {
            case .success(let response):
                // TODO: Handle response.
            case .failure(let error):
                // TODO: Handle error.
            }
        }
    }

しかし、この状態で検索を行うと下記のようなエラーが発生します。

AlgoliaSearchClient.ErrorMessage? (description = "invalid setting for restrictSearchableAttributes, attribute fieldId is not in searchableAttributes setting")

エラーの通り、Algolia では searchableAttributes という検索対象の属性指定がない場合に .restrictSearchableAttributes を使用すると検索が無効になるようです。searchableAttributes が空の場合は全ての属性が検索対象となるそうなので、とりあえず検索に必要な属性のみ適用していきます。今回はコンソールから指定しますが、それぞれの SDK からも変更することが可能なようです。

https://www.algolia.com/doc/api-reference/api-parameters/searchableAttributes/

ということで、下記のように searchableAttributes を設定しました。

f:id:yum_fishing:20210208191206p:plain

これで、再度検索を行うと fieldId の属性で検索を行えるようになりました🚀

参考

その他の記事

yamato8010.hatenablog.com

yamato8010.hatenablog.com

yamato8010.hatenablog.com