+PG_FUNCTION_INFO_V1(gin_count_estimate);
+Datum gin_count_estimate(PG_FUNCTION_ARGS);
+#if PG_VERSION_NUM >= 80300
+Datum
+gin_count_estimate(PG_FUNCTION_ARGS) {
+ text *name=PG_GETARG_TEXT_P(0);
+ Relation index;
+ TIDBitmap *bitmap = tbm_create(work_mem * 1024L);
+ IndexScanDesc scan;
+ int64 count;
+ char *relname=t2c(name);
+ ScanKeyData key;
+
+ index = gin_index_open(
+ makeRangeVarFromNameList(stringToQualifiedNameList(relname, "gin_count_estimate")));
+
+ if ( index->rd_opcintype[0] != TSVECTOROID ) {
+ gin_index_close(index);
+ elog(ERROR, "Column type is not a tsvector");
+ }
+
+ key.sk_flags = 0;
+ key.sk_attno = 1;
+ key.sk_strategy = TSearchStrategyNumber;
+ key.sk_subtype = 0;
+ key.sk_argument = PG_GETARG_DATUM(1);
+
+ fmgr_info( F_TS_MATCH_VQ , &key.sk_func );
+
+ scan = index_beginscan_bitmap(index, SnapshotNow, 1, &key);
+
+ count = index_getbitmap(scan, bitmap);
+ tbm_free(bitmap);
+
+ index_endscan( scan );
+ gin_index_close(index);
+
+
+ PG_RETURN_INT64(count);
+}
+#else
+Datum
+gin_count_estimate(PG_FUNCTION_ARGS) {
+ elog(NOTICE, "Function is not working under PgSQL < 8.3");
+
+ PG_RETURN_INT64(0);
+}
+#endif