Search code examples
couchbasesql++

How to delete documents with no subdocuments in couchbase?


I have a couchbase document with id x

x has no subdocument , As all were deleted in some subdoc operation , it is something like this {}

I want to delete all such empty docs with no subdocs. Is it possible in couchbase ,using an N1QL query or otherwise? I tried googling for solutions, but I found no relevant solutions.

Thanks for taking the time to read the question till the end.


Solution

  • The following query requires primary index.

    DELETE FROM default AS d
    WHERE d = {};
    

    The following query uses ix10 as covered index. Index contain only empty objects.

    CREATE INDEX ix10 ON default(OBJECT_LENGTH(self))
    WHERE OBJECT_LENGTH(self) = 0;
    
    DELETE FROM default AS d
    WHERE OBJECT_LENGTH(d) = 0;
    

    You can verify with the following data. The select should only give "k003"

    INSERT INTO default VALUES ("k001",1), VALUES ("k002",{"a":1}),  VALUES ("k003",{});
    
    SELECT META(d).id
    FROM default AS d
    WHERE OBJECT_LENGTH(d) = 0;