One thing with RavenDb that I’m constantly fighting especially while trying to learn it is managing indexes. I find myself constantly blowing my test database away only to recreate it, rebuild the indexes, and add new indexes as necessary. The most common practice I’ve seen so far is to manually manage these indexes since they only need to be built once. This doesn’t work for me since I’m lazy thus I needed a solution.
The solution which is fairly easy is to call the indexes api and parse out the returning Json. The API I’m using if called from localhost is http://localhost:8080/indexes. Let it be of note this is only necessary if you are using the Server/Service model. If using this in an embedded capacity then just access the indexes directly on the DocumentDatabase object.
I’ve created a simple extension method on the DocumentStore that will give me access to the information I want which is what indexes are created. Making it so I can preemptively query the database as to what I already have and only commit the deltas.
Here’s the C# solution for your viewing pleasure.
public static class IndexExtensions
{
public static IListGetIndexes(this DocumentStore store)
{
var client = new WebClient();
var result = client.DownloadString(
store.Configuration
.ServerUrl
.CombineUrl("indexes"));
var t = JsonConvert.DeserializeObject(result) as JArray;
return (from i in t
select i["name"]
.ToString()
.Replace("\"", ""))
.ToList();
}
public static string CombineUrl(this string baseUrl, string appendedUrl)
{
if (!baseUrl.EndsWith(@"/")) baseUrl += @"/";
var builder = new UriBuilder(baseUrl);
Uri newUri = null;
if (Uri.TryCreate(builder.Uri, appendedUrl, out newUri))
return newUri.ToString();
else
throw new ArgumentException("Unable to combine the specified url values");
}
}
Here's the F# solution if you are interested.
type System.String with
member x.CombineUrl(appendedUrl:string):string =
let k = match x with
| x when x.EndsWith(@"/") -> x
| _ -> x + @"/"
Uri.TryCreate((new UriBuilder(k)).Uri, appendedUrl) |>
function
| b, n when b -> n.ToString()
| _ -> failwith "Unable to combine url Values"
type Raven.Client.Document.DocumentStore with
member x.GetIndexes:list=
(new WebClient()).DownloadString (x.Configuration.ServerUrl.CombineUrl ("indexes"))
|> JArray.Parse
|> Seq.map (fun (i:JToken) -> i.Value("name"))
|> Seq.toList
0 comments:
Post a Comment