Created
February 26, 2018 15:56
-
-
Save brunomlopes/84bddb1b126e332cc63a5d8a70aecad1 to your computer and use it in GitHub Desktop.
Scripted index results which update statistics document save floats, but when doc is int, it's marked as a change
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class UnitTest : RavenTestBase | |
{ | |
[Fact] | |
public void ALoadShouldNotCauseADocumentToChange() | |
{ | |
var documentStore = NewDocumentStore(activeBundles:"ScriptedIndexResults"); | |
StoreScriptedIndexDefinition(documentStore); | |
using (var session = documentStore.OpenSession()) | |
{ | |
session.Store(new Comment {EntityId = "entity/1"}); | |
session.Store(new Comment {EntityId = "entity/1"}); | |
session.Store(new Stats {Id = "entity/1/statistics/comments"}); | |
session.SaveChanges(); | |
} | |
WaitForIndexing(documentStore); | |
using (var session = documentStore.OpenSession()) | |
{ | |
var s = session.Load<Stats>("entity/1/statistics/comments"); | |
Assert.Equal(2, s.Comments); | |
// doc is changed because an int has changed to a float | |
Assert.False(session.Advanced.HasChanged(s), "We only loaded the document, there should not be any changes"); | |
} | |
} | |
public class Comment | |
{ | |
public string Id { get; set; } | |
public string EntityId { get; set; } | |
} | |
class Stats | |
{ | |
public string Id { get; set; } | |
public int Comments { get; set; } | |
} | |
public class Comments_Stats : AbstractIndexCreationTask<Comment, Comments_Stats.CommentStats> | |
{ | |
public class CommentStats | |
{ | |
public string EntityId { get; set; } | |
public int Total { get; set; } | |
} | |
public Comments_Stats() | |
{ | |
Map = comments => comments | |
.Select(c => new | |
{ | |
c.EntityId, | |
Total = 1 | |
}); | |
Reduce = results => results | |
.GroupBy(e => e.EntityId) | |
.Select(g => new | |
{ | |
EntityId = g.Key, | |
Total = (int)g.Sum(x => x.Total) | |
}); | |
} | |
} | |
private static void StoreScriptedIndexDefinition(EmbeddableDocumentStore documentStore) | |
{ | |
using (var session = documentStore.OpenSession()) | |
{ | |
var indexScript = @" | |
var entityStats = LoadDocument(this.EntityId + '/statistics/comments'); | |
if(entityStats == null) return; | |
entityStats.Comments = this.Total; | |
PutDocument(this.EntityId + '/statistics/comments', entityStats, entityStats['@metadata']); | |
"; | |
documentStore.ExecuteIndex(new Comments_Stats()); | |
session.Store(new ScriptedIndexResults | |
{ | |
Id = ScriptedIndexResults.IdPrefix + new Comments_Stats().IndexName, | |
IndexScript = indexScript | |
}); | |
session.SaveChanges(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment