Dropping all couchbase indexes with bash script

Indexes are more important in Couchbase than usual relational databases and they have to be created and updated more often. Dropping an index can be done using a N1ql query, but when you have many indexes and you are updating them often it is taking time to update all queries for dropping indexes.  The script below is finding all of indexes in the system and will drop them in all buckets.

It is supposed that the couchbase has been installed on docker and there is no password for buckets. There are three different queries as main parts of script. The first one is finding all indexes and all buckets. The second one is removing primary index for a bucket and the last one removing indexes in a bucket one by one. The first for loop is looping over buckets and the second one over all indexes. The script is trying to remove an index from bucket regardless if it exists or not (If it doesn’t exist an error response will be the result of query).

The script can be improved but it gets the job done.

COMMAND="docker exec -i \${CONTAINER_NAME} sh -c 'cbq -q --engine=http://192.168.99.100:8093'"


indexes=$(cat <<EOF | eval ${COMMAND}
  SELECT name, keyspace_id FROM system:indexes;

EOF
)
bucketNames=$(echo "$indexes" | grep -Po '(?<="keyspace_id": ")[^"]*' | tr ' ' '\n' | sort -u | tr '\n' ' ')
indexNames=$(echo "$indexes" | grep -Po '(?<="name": ")[^"]*')
for bucketName in $bucketNames; do 
echo "removing indexes for " $bucketName
   echo DROP PRIMARY INDEX ON ${bucketName};
   cat <<EOF | eval ${COMMAND} 
      DROP PRIMARY INDEX ON ${bucketName};  
EOF

  for indexName in $indexNames; do 

   echo "removing index with name: " $indexName
   echo DROP INDEX ${bucketName}.${indexName};
   cat <<EOF | eval ${COMMAND} 
      DROP INDEX ${bucketName}.${indexName};  
EOF

  done
done