MongoDB: Creare un Index via codice

L’argomento MongoDB è stato un tema caldo di questa settimana sul mio blog e siamo giunti al secondo articolo in poco tempo. Nel caso vi siete persi il post MongoDB: $graphLookup & Aggregate vi invito a guardarlo in quanto il DTO di esempio e la struttura delle variabili privati proviene dal precedente articolo.

MongoDB: Creare un Index via codice

Ammettiamo di volere migliorare aggiungere un nuovo indice per migliorare le performance di ricerca all’interno della nostra IMongoCollection.

Non mi perdo in chiacchere e passo direttamente al codice. Ho scritto il metodo CreateIndexAsync nel quale verrà creato un nuovo Index composto da

  • ParentID ASC
  • LastName DESC
  • FirstName ASC

Ha senso questo indice? Probabilmente no, ma volevo mostrarvi come comporre un nuovo Index componendolo tra più campi.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
public async Task CreateIndexAsync()
{
   var indexKeys = Builders<PeopleDTO>
       .IndexKeys
       .Ascending(x => x.ParentID)
       .Descending(x => x.LastName)
       .Ascending(x => x.FirstName);

   await _collection
       .Indexes
       .CreateOneAsync
       (
           new CreateIndexModel<PeopleDTO>
               (
                   indexKeys,
                   new CreateIndexOptions
                   {
                       Background = true
                   }
               )
       );
}

Il parametro CreateIndexOptions è facoltativo, quindi se non avete nulla da mettere al suo interno o lo passate vuoto oppure null. Oltre alla voce Background potete definire le seguenti voci:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public class CreateIndexOptions
{
	public CreateIndexOptions();
	public bool? Unique { get; set; }
	public int? TextIndexVersion { get; set; }
	public BsonDocument StorageEngine { get; set; }
	public int? SphereIndexVersion { get; set; }
	public bool? Sparse { get; set; }
	public string Name { get; set; }
	public double? Min { get; set; }
	public double? Max { get; set; }
	public string LanguageOverride { get; set; }
	public TimeSpan? ExpireAfter { get; set; }
	public string DefaultLanguage { get; set; }
	public Collation Collation { get; set; }
	public int? Bits { get; set; }
	public bool? Background { get; set; }
	public int? Version { get; set; }
	public BsonDocument Weights { get; set; }
}

Per i più attenti potrebbe balzare all’occhio la mancanza di BucketSize e non è stato un errore, ma una scelta voluta. Il perché ve lo spiego subito riportando qua sotto la sua definizione:

1
2
3
4
5
//
// Summary:
//Gets or sets the size of a geohash bucket.
[Obsolete("GeoHaystack indexes were deprecated in server version 4.4.")]
public double? BucketSize { get; set; }

Come avrete notato la parola Obsolete non è bellissima da usare, quindi se potete evitate di usarla.