Search code examples
node.jsmongodbmongodb-indexes

Mongo text index doesn't finish when nothing is returned


I am not sure I have the proper vocabulary to describe the error that I am having so bear with me.

Here is the general schema for the documents in my collection

{
   _id: ObjectId(),
   name: String,
   business: String,
   address: {
      search_type: Character,
      address: String,
      city: String,
      state: String,
      zip: Number
   }
}

I wanted to search based on the address.search_type so I created a text index for that fields in my collection.

{ 
  v: 1,
  key: { _fts: 'text', _ftsx: 1 },
  name: 'address.search_type_text',
  ns: 'admin.customer',
  default_language: 'none',
  weights: { 'address.search_type': 1 },
  language_override: 'language',
  textIndexVersion: 3 
}

Now I know that my data should really only have C, G, or T as a search type and when I run a find query on this collection with one of the supported search_types the query runs just fine.

db.collection('blah').find({'address.search_type':'C'}).limit(10).toArray(function(err, result){
    if(err) console.log(err);
    else console.log(result[0]);
    db.close();
});

But when I run this query with a address.search_type that should return 0 documents my query either never finishes or times out.

db.collection('blah').find({'address.search_type':'Z'}).limit(10).toArray(function(err, result){
    if(err) console.log(err);
    else console.log(result[0]);
    db.close();
});

Why would my query not finish running / timeout when there are supposed to be 0 documents but works just fine when it can find documents?


Solution

  • After playing around with different types of indexes I realized that I did not need a text index at all.

    This is probably an embarrassing mistake but hey I just started learning mongodb so whatever.

    Anyway, I realized that all I needed to do was the create a single field index on address.search_type.

    { v: 1,
      key: { 'address.Search_Type': 1 },
      name: 'address.Search_Type_1',
      ns: 'admin.customer' 
    }
    

    I am not still totally sure why the text index was not working since I had set the language to none, but it makes sense that all I would need is a single index.

    I think text index is mostly used for searching phrases or keywords in largeish blocks of text. So the fact that my search was looking for a single character might have been causing problems since that is not what the text index was intended to be used for.