/
AnonymousObjectToLuceneDocumentConverter.cs
302 lines (274 loc) · 11 KB
/
AnonymousObjectToLuceneDocumentConverter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
//-----------------------------------------------------------------------
// <copyright file="AnonymousObjectToLuceneDocumentConverter.cs" company="Hibernating Rhinos LTD">
// Copyright (c) Hibernating Rhinos LTD. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using Lucene.Net.Documents;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Raven.Abstractions;
using Raven.Abstractions.Data;
using Raven.Abstractions.Indexing;
using Raven.Abstractions.Linq;
using Raven.Database.Extensions;
using Raven.Database.Impl;
using Raven.Database.Linq;
using Raven.Json.Linq;
using DateTools = Lucene.Net.Documents.DateTools;
namespace Raven.Database.Indexing
{
public class AnonymousObjectToLuceneDocumentConverter
{
private const string NullValueMarker = "NULL_VALUE";
private readonly IndexDefinition indexDefinition;
private readonly List<int> multipleItemsSameFieldCount = new List<int>();
private readonly Dictionary<object, Field> fieldsCache = new Dictionary<object, Field>();
private readonly Dictionary<object, NumericField> numericFieldsCache = new Dictionary<object, NumericField>();
public AnonymousObjectToLuceneDocumentConverter(IndexDefinition indexDefinition)
{
this.indexDefinition = indexDefinition;
}
public IEnumerable<AbstractField> Index(object val, PropertyDescriptorCollection properties, IndexDefinition indexDefinition, Field.Store defaultStorage)
{
return (from property in properties.Cast<PropertyDescriptor>()
let name = property.Name
where name != Constants.DocumentIdFieldName
let value = property.GetValue(val)
from field in CreateFields(name, value, indexDefinition, defaultStorage)
select field);
}
public IEnumerable<AbstractField> Index(RavenJObject document, IndexDefinition indexDefinition, Field.Store defaultStorage)
{
return (from property in document
let name = property.Key
where name != Constants.DocumentIdFieldName
let value = GetPropertyValue(property.Value)
from field in CreateFields(name, value, indexDefinition, defaultStorage)
select field);
}
private static object GetPropertyValue(RavenJToken property)
{
switch (property.Type)
{
case JTokenType.Array:
case JTokenType.Object:
return property.ToString(Formatting.None);
default:
return property.Value<object>();
}
}
/// <summary>
/// This method generate the fields for indexing documents in lucene from the values.
/// Given a name and a value, it has the following behavior:
/// * If the value is enumerable, index all the items in the enumerable under the same field name
/// * If the value is null, create a single field with the supplied name with the unanalyzed value 'NULL_VALUE'
/// * If the value is string or was set to not analyzed, create a single field with the supplied name
/// * If the value is date, create a single field with millisecond precision with the supplied name
/// * If the value is numeric (int, long, double, decimal, or float) will create two fields:
/// 1. with the supplied name, containing the numeric value as an unanalyzed string - useful for direct queries
/// 2. with the name: name +'_Range', containing the numeric value in a form that allows range queries
/// </summary>
private IEnumerable<AbstractField> CreateFields(string name, object value, IndexDefinition indexDefinition, Field.Store defaultStorage)
{
if(string.IsNullOrWhiteSpace(name))
throw new ArgumentException("Field must be not null, not empty and cannot contain whitespace", "name");
if (char.IsLetter(name[0]) == false &&
name[0] != '_')
{
name = "_" + name;
}
if (value == null)
{
yield return CreateFieldWithCaching(name, Constants.NullValue, indexDefinition.GetStorage(name, defaultStorage),
Field.Index.NOT_ANALYZED_NO_NORMS);
yield break;
}
if(Equals(value, string.Empty))
{
yield return CreateFieldWithCaching(name, Constants.EmptyString, indexDefinition.GetStorage(name, defaultStorage),
Field.Index.NOT_ANALYZED_NO_NORMS);
yield break;
}
if (value is DynamicNullObject)
{
if(((DynamicNullObject)value ).IsExplicitNull)
{
yield return CreateFieldWithCaching(name, Constants.NullValue, indexDefinition.GetStorage(name, defaultStorage),
Field.Index.NOT_ANALYZED_NO_NORMS);
}
yield break;
}
if(value is AbstractField)
{
yield return (AbstractField)value;
yield break;
}
var itemsToIndex = value as IEnumerable;
if( itemsToIndex != null && ShouldTreatAsEnumerable(itemsToIndex))
{
yield return new Field(name + "_IsArray", "true", Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS);
int count = 1;
foreach (var itemToIndex in itemsToIndex)
{
multipleItemsSameFieldCount.Add(count++);
foreach (var field in CreateFields(name, itemToIndex, indexDefinition, defaultStorage))
{
yield return field;
}
multipleItemsSameFieldCount.RemoveAt(multipleItemsSameFieldCount.Count - 1);
}
yield break;
}
var fieldIndexingOptions = indexDefinition.GetIndex(name, null);
if (fieldIndexingOptions == Field.Index.NOT_ANALYZED || fieldIndexingOptions == Field.Index.NOT_ANALYZED_NO_NORMS)// explicitly not analyzed
{
if (value is DateTime)
{
var val = (DateTime) value;
yield return CreateFieldWithCaching(name, val.ToString(Default.DateTimeFormatsToWrite), indexDefinition.GetStorage(name, defaultStorage),
indexDefinition.GetIndex(name, Field.Index.NOT_ANALYZED_NO_NORMS));
}
else if(value is DateTimeOffset)
{
var val = (DateTimeOffset)value;
yield return CreateFieldWithCaching(name, val.ToString(Default.DateTimeFormatsToWrite), indexDefinition.GetStorage(name, defaultStorage),
indexDefinition.GetIndex(name, Field.Index.NOT_ANALYZED_NO_NORMS));
}
else
{
yield return CreateFieldWithCaching(name, value.ToString(), indexDefinition.GetStorage(name, defaultStorage),
indexDefinition.GetIndex(name, Field.Index.NOT_ANALYZED_NO_NORMS));
}
yield break;
}
if (value is string)
{
var index = indexDefinition.GetIndex(name, Field.Index.ANALYZED);
yield return CreateFieldWithCaching(name, value.ToString(), indexDefinition.GetStorage(name, defaultStorage),
index);
yield break;
}
if (value is DateTime)
{
yield return CreateFieldWithCaching(name, DateTools.DateToString((DateTime)value, DateTools.Resolution.MILLISECOND),
indexDefinition.GetStorage(name, defaultStorage),
indexDefinition.GetIndex(name, Field.Index.NOT_ANALYZED_NO_NORMS));
}
else if (value is DateTimeOffset)
{
yield return CreateFieldWithCaching(name, DateTools.DateToString(((DateTimeOffset)value).DateTime, DateTools.Resolution.MILLISECOND),
indexDefinition.GetStorage(name, defaultStorage),
indexDefinition.GetIndex(name, Field.Index.NOT_ANALYZED_NO_NORMS));
}
else if(value is bool)
{
yield return new Field(name, ((bool) value) ? "true" : "false", indexDefinition.GetStorage(name, defaultStorage),
indexDefinition.GetIndex(name, Field.Index.NOT_ANALYZED_NO_NORMS));
}
else if(value is IConvertible) // we need this to store numbers in invariant format, so JSON could read them
{
var convert = ((IConvertible) value);
yield return CreateFieldWithCaching(name, convert.ToString(CultureInfo.InvariantCulture), indexDefinition.GetStorage(name, defaultStorage),
indexDefinition.GetIndex(name, Field.Index.NOT_ANALYZED_NO_NORMS));
}
else if (value is IDynamicJsonObject)
{
var inner = ((IDynamicJsonObject)value).Inner;
yield return CreateFieldWithCaching(name + "_ConvertToJson", "true", Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS);
yield return CreateFieldWithCaching(name, inner.ToString(), indexDefinition.GetStorage(name, defaultStorage),
indexDefinition.GetIndex(name, Field.Index.NOT_ANALYZED_NO_NORMS));
}
else
{
yield return CreateFieldWithCaching(name + "_ConvertToJson", "true", Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS);
yield return CreateFieldWithCaching(name, RavenJToken.FromObject(value).ToString(), indexDefinition.GetStorage(name, defaultStorage),
indexDefinition.GetIndex(name, Field.Index.NOT_ANALYZED_NO_NORMS));
}
foreach (var numericField in CreateNumericFieldWithCaching(name, value, defaultStorage))
yield return numericField;
}
private IEnumerable<AbstractField> CreateNumericFieldWithCaching(string name, object value,
Field.Store defaultStorage)
{
var fieldName = name + "_Range";
var storage = indexDefinition.GetStorage(name, defaultStorage);
var cacheKey = new
{
fieldName,
storage,
multipleItemsSameFieldCountSum = multipleItemsSameFieldCount.Sum()
};
NumericField numericField;
if (numericFieldsCache.TryGetValue(cacheKey, out numericField) == false)
{
numericFieldsCache[cacheKey] = numericField = new NumericField(fieldName, storage, true);
}
if (value is int)
{
if (indexDefinition.GetSortOption(name) == SortOptions.Long)
yield return numericField.SetLongValue((int) value);
else
yield return numericField.SetIntValue((int) value);
}
if (value is long)
{
yield return numericField
.SetLongValue((long) value);
}
if (value is decimal)
{
yield return numericField
.SetDoubleValue((double) (decimal) value);
}
if (value is float)
{
if (indexDefinition.GetSortOption(name) == SortOptions.Double)
yield return numericField.SetDoubleValue((float) value);
else
yield return numericField.SetFloatValue((float) value);
}
if (value is double)
{
yield return numericField
.SetDoubleValue((double) value);
}
}
private static bool ShouldTreatAsEnumerable(IEnumerable itemsToIndex)
{
if (itemsToIndex == null)
return false;
if (itemsToIndex is DynamicJsonObject)
return false;
if (itemsToIndex is string)
return false;
if (itemsToIndex is RavenJObject)
return false;
if (itemsToIndex is IDictionary)
return false;
return true;
}
private Field CreateFieldWithCaching(string name, string value, Field.Store store, Field.Index index)
{
var cacheKey = new
{
name,
index,
store,
multipleItemsSameFieldCountSum = multipleItemsSameFieldCount.Sum()
};
Field field;
if (fieldsCache.TryGetValue(cacheKey, out field) == false)
{
fieldsCache[cacheKey] = field = new Field(name, value, store, index);
}
field.SetValue(value);
return field;
}
}
}