How to know if query doesn't return documents

前端 未结 2 1916
我寻月下人不归
我寻月下人不归 2021-01-22 12:47

How can I know if docs is empty? I can\'t do len(docs)

docs = query.stream()
for doc in docs:
    // do something

I need to know i

相关标签:
2条回答
  • 2021-01-22 13:24

    Since stream() returns a generator, there won't be a trivial way to determine if it is empty without actually reading it.

    By far the simplest solution would delay knowing until after you are past the loop. Something like this:

    docs = query.stream()
    stream_empty = True
    for doc in docs:
      stream_empty = False
      # do something
    
    if stream_empty:
      print("it was empty")
    else:
      print("it wasn't empty")
    

    Otherwise, you get into having to build your own generator around the stream's generator that allows peeking. See this question.

    0 讨论(0)
  • 2021-01-22 13:26

    Instead of using the generator returned by stream() you can directly user the query and its method get().

    The get method runs the query and gathers the documents within a list that you can access. This list is empty if no document match the query.

    docs = query.get()
    if not docs:
        # do something
    else : 
        for doc in docs :
            doc = doc.to_dict()
            # do something
    
    0 讨论(0)
提交回复
热议问题