Add a field to a document in raven 3.5 where the property doesn't exist - ravendb

In my instance of raven3.5 I have a collection and some documents have an extra property due to a change in the document structure. Now I need to query on that property but many older documents don't have it.
How can I patch the collection and add the property to documents that don't have it? Or create a query that will get the documents that don't have the specific property?
Thanks.

The below is what I know works for RavenDB Server 4.2 and up:
Option 1 - using static index
Create a static index ('MyIndex') with the following map method:
from i in docs.Items
select new {
Name = i.Name
}
Then query the index as follows:
Return all 'Items' that do not have 'Name':
from index 'MyIndex'
where true and not exists(Name)
Option 2 - using auto-index:
First, run the following query which will 'create' the auto-index for you:
from Items
where exists(Name)
After that, you can query the following to get results:
from Items
where true and not exists(Name)
=================================================
A patch script is made up of the query part and the update part
So use the following to add the missing property to docs that don't have it:
from Items
where true and not exists(Name)
update {
this.Name = "value"
}

Related

Sitefinity - Safely delete orphaned dynamic content records

I've been adding records to a dynamic module via the API and in the process during my experimentation I added a bunch of records that weren't associated correctly with any valid parent record.
I've checked and so far I can see that Sitefinity stores data about these records in a number of tables:
mydynamiccontenttype_table
sf_dynamic_content
sf_dynmc_cntnt_sf_lnguage_data
sf_dynmc_cntent_sf_permissions
I would like to clean up the database by deleting these records but I want to make sure I don't create more problems in the process.
Anyone know if there are more references to these dynamic content type records or a process to safely delete them?
There are probably other tables, so your safest option would be to delete the items using the Sitefinity API.
Just get the masterId of the item and use a code like this:
public static void DeleteDataItemOfType(this DynamicModuleManager manager, string type, Guid Id)
{
Type resolvedType = TypeResolutionService.ResolveType(type);
using (var region = new ElevatedModeRegion(manager))
{
manager.DeleteDataItem(resolvedType, Id);
manager.SaveChanges();
}
}

Raven DB patch request not running on start

I currently have a ravenDB database with a model that has a specific set of fields that I have been working with. I realized there is a field or two that I need to add and have successfully used ravenDB's patch request once to patch my documents in my database to initialize those fields on all the pre existing documents. I wanted to add another field again but I cannot get the patch code to run again to update my documents another time. I was wondering if someone could tell me if there was any documentation or methods to check the database at deploy and see if the models are the same, if not to patch the ones that are not but leave the ones that are alone and ensure after an update the pre existing models are not reset to what the patch is patching.
private void updateDb(IDocumentStore store)
{
store.DatabaseCommands.UpdateByIndex("Interviews_ByCandidateInterviewAndDate",
new IndexQuery{
Query = "Candidate:"
},
new []{
new PatchRequest{
Type = PatchCommandType.Set,
Name = "IsArchived",
Value = true
},
new PatchRequest{
Type = PatchCommandType.Set,
Name = "ArchiveDate",
Value = null
},
new PatchRequest{
Type = PatchCommandType.Set,
Name = "TestingField",
Value = 14
}
},
new BulkOperationOptions
{
AllowStale = false
}
);
}
The first two patch requests went through and shows up in the database but one thing I cannot see is if i were to run this patch again to get that third field into the model, would it change all the values that are already existing in the database for the first two to true and null or would it leave them the way they are and more importantly, I cannot get this code to run again.
Any pointers in the right direction would be greatly appreciated! thanks.
You query is wrong:
Query = "Candidate:"
Should have no results (invalid query).
Use:
Query = "Candidate:*"

RavenDB Index created incorrectly

I have a document in RavenDB that looks looks like:
{
"ItemId": 1,
"Title": "Villa
}
With the following metadata:
Raven-Clr-Type: MyNamespace.Item, MyNamespace
Raven-Entity-Name: Doelkaarten
So I serialized with a type MyNamespace.Item, but gave it my own Raven-Entity-Name, so it get its own collection.
In my code I define an index:
public class DoelkaartenIndex : AbstractIndexCreationTask<Item>
{
public DoelkaartenIndex()
{
// MetadataFor(doc)["Raven-Entity-Name"].ToString() == "Doelkaarten"
Map = items => from item in items
where MetadataFor(item)["Raven-Entity-Name"].ToString() == "Doelkaarten"
select new {Id = item.ItemId, Name = item.Title};
}
}
In the Index it is translated in the "Maps" field to:
docs.Items
.Where(item => item["#metadata"]["Raven-Entity-Name"].ToString() == "Doelkaarten")
.Select(item => new {Id = item.ItemId, Name = item.Title})
A query on the index never gives results.
If the Maps field is manually changed to the code below it works...
from doc in docs
where doc["#metadata"]["Raven-Entity-Name"] == "Doelkaarten"
select new { Id = doc.ItemId, Name=doc.Title };
How is it possible to define in code the index that gives the required result?
RavenDB used: RavenHQ, Build #961
UPDATE:
What I'm doing is the following: I want to use SharePoint as a CMS, and use RavenDB as a ready-only replication of the SharePoint list data. I created a tool to sync from SharePoint lists to RavenDB. I have a generic type Item that I create from a SharePoint list item and that I serialize into RavenDB. So all my docs are of type Item. But they come from different lists with different properties, so I want to be able to differentiate. You propose to differentiate on an additional property, this would perfectly work. But then I will see all list items from all lists in one big Items collection... What would you think to be the best approach to this problem? Or just live with it? I want to use the indexes to create projections from all data in an Item to the actual data that I need.
You can't easily change the name of a collection this way. The server-side will use the Raven-Entity-Name metadata, but the client side will determine the collection name via the conventions registered with the document store. The default convention being to use the type name of the entity.
You can provide your own custom convention by assigning a new function to DocumentStore.Conventions.FindTypeTagName - but it would probably be cumbersome to do that for every entity. You could create a custom attribute to apply to your entities and then write the function to look for and understand that attribute.
Really the simplest way is just to call your entity Doelkaarten instead of Item.
Regarding why the change in indexing works - it's not because of the switch in linq syntax. It's because you said from doc in docs instead of from doc in docs.Items. You probably could have done from doc in docs.Doelkaartens instead of using the where clause. They are equivalent. See this page in the docs for further examples.

fetch single property in object from database

I am working on NET MVC 3.0 and Nhibernate 3.0. I want to fetch only one property from database to an object.
For instance, suppose I have a class Module. I want to select all the names from module table (like select modulename from module query) and an prepare a list of module objects which have only name. All other properties can be null.
I tried this using QueryOver API:
IQueryOver<ProjectModule> module = session.QueryOver<ProjectModule>()
.Select(a=>a.Name)
.TransformUsing(
NHibernate.Transform.Transformers.AliasToBean<ProjectModule>());
pm = module.List<ProjectModule>();
pm is IList<ProjectModule> type.
Transaction gets committed successfully. No error occurred, but I get a list of module objects with all properties = null. Module name null, module id null etc.
I checked what query is executing on SQL using NUnit and got this: SELECT this_Name as y0_ FROM ProjectModule this_.
To be more accurate create a DTO object, assume ProjectModuleDto, that will contain only the Name. It's not a good practice to use the the domain object with uninitialized values through your code, cause it creates confusions of filled data in various scenarious.
And the fllowing code will do the trick - populate the list of DTOs: ProjectModuleDto with correct Name of project module from database:
ProjectModuleDto projectModuleDto = null;
IQueryOver<ProjectModule> module = session.QueryOver<ProjectModule>()
.SelectList(
list=>list.Select(a => a.Name).WithAlias(() => projectModuleDto.Name)
)
TransformUsing(NHibernate.Transform.Transformers.AliasToBean<ProjectModuleDto>());
pm = module.List<ProjectModuleDto>();
If you are fetching only a single property, you don't need to use transformers. Try to use a List<string> directly:
var moduleNames = session.QueryOver<ProjectModule>()
.Select(a => a.Name)
.List<string>();
Read more about QueryOver syntax on NHibernate blog.
Is this what you're looking for?
List<ProjectModule> result = new List<ProjectModule>();
session.QueryOver<ProjectModule>()
.Select(a => a.Name)
.ToList().ForEach(delegate(string mName)
{
result.Add(ProjectModule() { Name = mName });
});

Check if property exists in RavenDB

I want to add property to existing document (using clues form http://ravendb.net/docs/client-api/partial-document-updates). But before adding want to check if that property already exists in my database.
Is any "special,proper ravendB way" to achieve that?
Or just load document and check if this property is null or not?
You can do this using a set based database update. You carry it out using JavaScript, which fortunately is similar enough to C# to make it a pretty painless process for anybody. Here's an example of an update I just ran.
Note: You have to be very careful doing this because errors in your script may have undesired results. For example, in my code CustomId contains something like '1234-1'. In my first iteration of writing the script, I had:
product.Order = parseInt(product.CustomId.split('-'));
Notice I forgot the indexer after split. The result? An error, right? Nope. Order had the value of 12341! It is supposed to be 1. So be careful and be sure to test it thoroughly.
Example:
Job has a Products property (a collection) and I'm adding the new Order property to existing Products.
ravenSession.Advanced.DocumentStore.DatabaseCommands.UpdateByIndex(
"Raven/DocumentsByEntityName",
new IndexQuery { Query = "Tag:Jobs" },
new ScriptedPatchRequest { Script =
#"
this.Products.Map(function(product) {
if(product.Order == undefined)
{
product.Order = parseInt(product.CustomId.split('-')[1]);
}
return product;
});"
}
);
I referenced these pages to build it:
set based ops
partial document updates (in particular the Map section)