3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Swift FireStore でwhereFieldとorderを同時に使いたい!

Last updated at Posted at 2022-07-15

目的

Swiftを用いた開発で、FireStoreの whereField と order を同時に使用する方法を述べること
whereFieldの対象要素 ≠ orderの対象要素の時だけ

結論!

コンソール画面に出てくるURLへアクセスして「複合インデックス」を作成して、5分後同じプログラムで実行し直す

解決策!

複合インデックスを作成して、5分くらい待つ (参考サイト)


複合インデックスの作成方法
コンソール画面にURLが出ているので、それにアクセスして、説明されるままインデックスを作成する。

The query requires an index. You can create it here: https://console.firebase.google.com/xxxxx....

なぜ5分まつ?
複合インデックスが反映されるまでに時間がかかったから。
※ 筆者だけかもしれません。筆者は反映の確認を5分後にとれました。

この記事どういう時に使えるの?

「whereField と order を使って情報を取ってきたい。のに、なぜか取得できない! なぜ❓」 という人がいる時。


具体的に、下のFireStoreモデル図やプログラムをもとに『日本国籍のユーザーをid順に取得したい』という場合を考える。
whereFieldで国籍を指定, orderでid順に並び替え を行う。が、うまくいかない!

FireStoreモデル図.
"Users"
    |_   userId01  --  "country" : "Japan"
         userId02      "id"      : 1
            ・
                      ・
                      ・

FetchJapaneseUserModel.swift
・・・

// 日本国籍のユーザードキュメントをid順に並び替え取得する
let userRef = Firestore.firestore().collection("Users")      
userRef
    .whereField("country", isEqualTo: "Japan")
    .order(by: "id")

・・・

なぜうまくいかない!?

orderの要素 = whereFieldの要素 が原則だから。

👇 参考サイトより抜粋

FetchJapaneseUserModel.swift
・・・

// 🙆‍♂️ → id順に並び替えたいのに、国籍順に並び替えている。意味ない!
let userRef = Firestore.firestore().collection("Users")         
userRef
    .whereField("country", isEqualTo: "Japan")
    .order(by: "country")


// 🙅‍♂️
let userRef = Firestore.firestore().collection("Users")        
userRef
    .whereField("country", isEqualTo: "Japan")
    .order(by: "id")

・・・

確認

同じプログラムで再度実行すると、日本国籍のユーザードキュメントをid順に並び替え取得を行えた ✌️

補足 : whereField, order とは?

whereField : 条件に一致するものを通す
order : 並び替える (昇順:Ascending, 降順:Descending)

参考サイト

3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?