programing

Firestore: 부등식/비등식 쿼리를 수행하는 방법

css3 2023. 7. 9. 12:34

Firestore: 부등식/비등식 쿼리를 수행하는 방법

저는 파이어스토어 컬렉션에서 제가 작성하지 않은 기사만 선택하고 싶습니다.
정말 그렇게 어렵습니까?

모든 아티클에는 "owner_uid" 필드가 있습니다.

이상입니다.
나는 단지 동등한 것을 쓰고 싶을 뿐입니다."select * from articles where uid<>request.auth.uid"

TL;DR: 솔루션이 이미 발견되었습니다. 언어/언어에 대한 사용: https://firebase.google.com/docs/firestore/query-data/queries#kotlin+ktx_5

2020년 9월 18일 편집

파이어베이스 릴리스 노트에 따르면 지금은not-in그리고.!=쿼리. (이제 올바른 설명서를 사용할 수 있습니다.)

  • not-in지정된 필드의 값이 지정된 배열에 없는 문서를 찾습니다.
  • !=지정된 필드의 값이 지정된 값과 동일하지 않은 문서를 찾습니다.

두 쿼리 연산자 모두 지정된 필드가 없는 문서와 일치하지 않습니다.해당 언어의 구문에 대한 설명서를 참조하십시오.

원답

소방서는 불평등 검사를 제공하지 않습니다.설명서에 따르면:

where() 메서드는 필터링할 필드, 비교 작업 및 값의 세 가지 매개 변수를 사용합니다.비교는 <, <=, ==, > 또는 >=일 수 있습니다.

불평등 연산은 지수를 사용하는 다른 연산처럼 확장되지 않습니다.Firestore 인덱스는 범위 쿼리에 적합합니다.이러한 유형의 인덱스를 사용하면 불평등 쿼리의 경우 백엔드가 결과를 얻기 위해 컬렉션의 모든 문서를 검색해야 하므로 문서 수가 증가하면 성능이 매우 저하됩니다.

특정 항목을 제거하기 위해 결과를 필터링해야 하는 경우에도 로컬에서 제거할 수 있습니다.

여러 쿼리를 사용하여 고유한 값을 제외할 수도 있습니다.12개 빼고 다 원하면 이런 거.값 < 12에 대해 쿼리한 다음 값 > 12에 대해 쿼리한 다음 클라이언트에서 결과를 병합합니다.

Android의 경우 Task API로 쉽게 구현할 수 있어야 합니다.초보자의 예:

    FirebaseFirestore db = FirebaseFirestore.getInstance();
    Query lessQuery = db.collection("users").whereLessThan("uid", currentUid);
    Query greaterQuery = db.collection("users").whereGreaterThan("uid", currentUid);
    Task lessQuery Task = firstQuery.get();
    Task greaterQuery = secondQuery.get();

    Task combinedTask = Tasks.whenAllSuccess(lessQuery , greaterQuery)
                             .addOnSuccessListener(new OnSuccessListener<List<Object>>() {
        @Override
        public void onSuccess(List<Object> list) {

            //This is the list of "users" collection without user with currentUid
        }
    });

또한 이를 통해 모든 쿼리 집합을 결합할 수 있습니다.

웹에는 rxfire가 있습니다.

다음은 JavaScript에서 문제를 해결한 방법의 예입니다.

let articlesToDisplay = await db
  .collection('articles')
  .get()
  .then((snapshot) => {
    let notMyArticles = snapshot.docs.filter( (article) => 
      article.data().owner_uid !== request.auth.uid
    )
    return notMyArticles
  })

모든 문서를 가져오고 Array.prototype을 사용합니다.필터(filter)는 원하지 않는 항목을 필터링합니다.서버 측 또는 클라이언트 측에서 실행할 수 있습니다.

"TypeError: 원형 구조를 JSON으로 변환"을 일으킨 Darren G의 답변 업데이트.필터 작업을 수행할 때 데이터가 아닌 전체 Firebase 개체가 어레이에 다시 추가되었습니다.우리는 필터 방식과 방식을 연결하여 이를 해결할 수 있습니다.

let articles = []
let articlesRefs = await db.collection('articles').get();

articles = articlesRefs.docs
           .filter((article) => article.data.uid !== request.auth.uid) //Get Filtered Docs
           .map((article) => article.data()); //Process Docs to Data

return articles

참고: 데이터베이스에서 모든 문서를 가져온 다음 로컬로 필터링하기 때문에 비용이 많이 드는 작업입니다.

  1. 하나 또는 두 개의 문서에서 모든 사용자 ID 추적

  2. 원치 않는 ID 필터링

  3. "위치" 사용


var mylistofidwherenotme =  // code to fetch the single document where you tracked all user id, then filter yourself out


database.collection("articles").where("blogId", "in", mylistofidwherenotme)

let query = docRef.where('role','>',user_role).where('role','<',user_role).get()

문자열 값이 있는 Firestore에서 "비등" 작업으로 작동하지 않습니다.

Javascript 코드 내에서 객체의 배열을 필터링할 수 있습니다.

var data=[Object,Object,Object] // this is your object array
var newArray = data.filter(function(el) {
   return el.gender != 'Male';
});

언급URL : https://stackoverflow.com/questions/47251919/firestore-how-to-perform-a-query-with-inequality-not-equals