With Sitecore 7, the Sitecore index (based on Lucene.NET) have greatly improved, thus making the index even more usable.
One thing you should know though, is that when you add items to Sitecore using the Sitecore.Data.Items.Item.Add() method, the index is not immediately updated. The index is updated shortly after, but the time varies depending on your index update strategy.
The result is that if you query the index just after you added a new item, it is not a given that the item exists in the index.
There is a solution to this (of course, this is Sitecore). When you have added the new item, you must manually update the search index for this specific item.
I have made an Extension Method to show how this can be done:
using System; using System.Linq; using Lucene.Net.Index; using Sitecore.ContentSearch; using Sitecore.Data; using Sitecore.Data.Items; using Sitecore.Diagnostics; namespace MyProject { public static class ItemExtensions { public static Item AddAndUpdate(this Item item, string name, TemplateID templateID) { Assert.ArgumentNotNull(item, "item"); Assert.IsTrue(item.Database.Name.ToLower() == "master", "Could not add item to " + item.Paths.FullPath + ": item is not in the 'master' database"); Item newItem = item.Add(ItemUtil.ProposeValidItemName(name), templateID); Log.Audit("Item create: " + AuditFormatter.FormatItem(newItem), typeof(ItemExtensions)); var tempItem = (SitecoreIndexableItem)newItem; ContentSearchManager.GetIndex("sitecore_master_index").Refresh(tempItem); return newItem; } } }
The trick lies within these 2 lines of code:
var tempItem = (SitecoreIndexableItem)newItem; ContentSearchManager.GetIndex("sitecore_master_index").Refresh(tempItem);
First the item is converted into a SitecoreIndexableItem, and then the master index is refreshed for this single item.
The extension method can be used like this:
using MyProject; namespace MyNamespace { public void AddItem(Item parent, string name, TemplateID templateID) { Item newItem = parent.AddAndUpdate(name, templateID); } }
Please note that this will increase the time to create an item substantially, from barely mesureable milliseconds to a full second or so.
MORE TO READ:
- Sitecore 7 Add Single Item to Index by Mike Robbins.
- Sitecore 7: Index Update Strategies by John West.
