Skip to content

Commit 8e8ce96

Browse files
authored
value_count Aggregation optimization (#54854)
We found some problems during the test. Data: 200Million docs, 1 shard, 0 replica hits | avg | sum | value_count | ----------- | ------- | ------- | ----------- | 20,000 | .038s | .033s | .063s | 200,000 | .127s | .125s | .334s | 2,000,000 | .789s | .729s | 3.176s | 20,000,000 | 4.200s | 3.239s | 22.787s | 200,000,000 | 21.000s | 22.000s | 154.917s | The performance of `avg`, `sum` and other is very close when performing statistics, but the performance of `value_count` has always been poor, even not on an order of magnitude. Based on some common-sense knowledge, we think that `value_count` and sum are similar operations, and the time consumed should be the same. Therefore, we have discussed the agg of `value_count`. The principle of counting in es is to traverse the field of each document. If the field is an ordinary value, the count value is increased by 1. If it is an array type, the count value is increased by n. However, the problem lies in traversing each document and taking out the field, which changes from disk to an object in the Java language. We summarize its current problems with Elasticsearch as: - Number cast to string overhead, and GC problems caused by a large number of strings - After the number type is converted to string, sorting and other unnecessary operations are performed Here is the proof of type conversion overhead. ``` // Java long to string source code, getChars is very time-consuming. public static String toString(long i) { int size = stringSize(i); if (COMPACT_STRINGS) { byte[] buf = new byte[size]; getChars(i, size, buf); return new String(buf, LATIN1); } else { byte[] buf = new byte[size * 2]; StringUTF16.getChars(i, size, buf); return new String(buf, UTF16); } } ``` test type | average | min | max | sum ------------ | ------- | ---- | ----------- | ------- double->long | 32.2ns | 28ns | 0.024ms | 3.22s long->double | 31.9ns | 28ns | 0.036ms | 3.19s long->String | 163.8ns | 93ns | 1921 ms | 16.3s #36752 The program heat map shows that the toString time is particularly serious. ## optimization Our optimization code is actually very simple. It is to manage different types separately, instead of uniformly converting to string unified processing. We added type identification in ValueCountAggregator, and made special treatment for number and geopoint types to cancel their type conversion. Because the string type is reduced and the string constant is reduced, the improvement effect is very obvious. ## result hits | avg | sum | value_count | value_count | value_count | value_count | value_count | value_count | | | | double | double | keyword | keyword | geo_point | geo_point | | | | before | after | before | after | before | after | ----------- | ------- | ------- | ----------- | ----------- | ----------- | ----------- | ----------- | ----------- | 20,000 | 38s | .033s | .063s | .026s | .030s | .030s | .038s | .015s | 200,000 | 127s | .125s | .334s | .078s | .116s | .099s | .278s | .031s | 2,000,000 | 789s | .729s | 3.176s | .439s | .348s | .386s | 3.365s | .178s | 20,000,000 | 4.200s | 3.239s | 22.787s | 2.700s | 2.500s | 2.600s | 25.192s | 1.278s | 200,000,000 | 21.000s | 22.000s | 154.917s | 18.990s | 19.000s | 20.000s | 168.971s | 9.093s | - The results are more in line with common sense. `value_count` is about the same as `avg`, `sum`, etc., or even lower than these. Previously, `value_count` was much larger than avg and sum, and it was not even an order of magnitude when the amount of data was large. - When calculating numeric types such as `double` and `long`, the performance is improved by about 8 to 9 times; when calculating the `geo_point` type, the performance is improved by 18 to 20 times.
1 parent 1328e4b commit 8e8ce96

File tree

2 files changed

+70
-5
lines changed

2 files changed

+70
-5
lines changed

server/src/main/java/org/elasticsearch/search/aggregations/metrics/ValueCountAggregator.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,11 @@
1919
package org.elasticsearch.search.aggregations.metrics;
2020

2121
import org.apache.lucene.index.LeafReaderContext;
22+
import org.apache.lucene.index.SortedNumericDocValues;
2223
import org.elasticsearch.common.lease.Releasables;
2324
import org.elasticsearch.common.util.BigArrays;
2425
import org.elasticsearch.common.util.LongArray;
26+
import org.elasticsearch.index.fielddata.MultiGeoPointValues;
2527
import org.elasticsearch.index.fielddata.SortedBinaryDocValues;
2628
import org.elasticsearch.search.aggregations.Aggregator;
2729
import org.elasticsearch.search.aggregations.InternalAggregation;
@@ -62,6 +64,34 @@ public LeafBucketCollector getLeafCollector(LeafReaderContext ctx,
6264
return LeafBucketCollector.NO_OP_COLLECTOR;
6365
}
6466
final BigArrays bigArrays = context.bigArrays();
67+
68+
if (valuesSource instanceof ValuesSource.Numeric) {
69+
final SortedNumericDocValues values = ((ValuesSource.Numeric)valuesSource).longValues(ctx);
70+
return new LeafBucketCollectorBase(sub, values) {
71+
72+
@Override
73+
public void collect(int doc, long bucket) throws IOException {
74+
counts = bigArrays.grow(counts, bucket + 1);
75+
if (values.advanceExact(doc)) {
76+
counts.increment(bucket, values.docValueCount());
77+
}
78+
}
79+
};
80+
}
81+
if (valuesSource instanceof ValuesSource.Bytes.GeoPoint) {
82+
MultiGeoPointValues values = ((ValuesSource.GeoPoint)valuesSource).geoPointValues(ctx);
83+
return new LeafBucketCollectorBase(sub, null) {
84+
85+
@Override
86+
public void collect(int doc, long bucket) throws IOException {
87+
counts = bigArrays.grow(counts, bucket + 1);
88+
if (values.advanceExact(doc)) {
89+
counts.increment(bucket, values.docValueCount());
90+
}
91+
}
92+
};
93+
}
94+
// The following is default collector. Including the keyword FieldType
6595
final SortedBinaryDocValues values = valuesSource.bytesValues(ctx);
6696
return new LeafBucketCollectorBase(sub, values) {
6797

server/src/test/java/org/elasticsearch/search/aggregations/metrics/ValueCountAggregatorTests.java

Lines changed: 40 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,9 @@
2121

2222
import org.apache.lucene.document.BinaryDocValuesField;
2323
import org.apache.lucene.document.Document;
24+
import org.apache.lucene.document.DoubleDocValuesField;
2425
import org.apache.lucene.document.IntPoint;
26+
import org.apache.lucene.document.LatLonDocValuesField;
2527
import org.apache.lucene.document.NumericDocValuesField;
2628
import org.apache.lucene.document.SortedDocValuesField;
2729
import org.apache.lucene.document.SortedNumericDocValuesField;
@@ -76,8 +78,8 @@ public class ValueCountAggregatorTests extends AggregatorTestCase {
7678

7779
private static final String FIELD_NAME = "field";
7880

79-
/** Script to return the {@code _value} provided by aggs framework. */
80-
private static final String VALUE_SCRIPT = "_value";
81+
private static final String STRING_VALUE_SCRIPT = "string_value";
82+
private static final String NUMBER_VALUE_SCRIPT = "number_value";
8183
private static final String SINGLE_SCRIPT = "single";
8284

8385
@Override
@@ -99,7 +101,8 @@ protected List<ValuesSourceType> getSupportedValuesSourceTypes() {
99101
protected ScriptService getMockScriptService() {
100102
Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>();
101103

102-
scripts.put(VALUE_SCRIPT, vars -> (Double.valueOf((String) vars.get("_value")) + 1));
104+
scripts.put(STRING_VALUE_SCRIPT, vars -> (Double.valueOf((String) vars.get("_value")) + 1));
105+
scripts.put(NUMBER_VALUE_SCRIPT, vars -> (((Number) vars.get("_value")).doubleValue() + 1));
103106
scripts.put(SINGLE_SCRIPT, vars -> 1);
104107

105108
MockScriptEngine scriptEngine = new MockScriptEngine(MockScriptEngine.NAME,
@@ -110,6 +113,38 @@ protected ScriptService getMockScriptService() {
110113
return new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS);
111114
}
112115

116+
117+
public void testGeoField() throws IOException {
118+
testCase(new MatchAllDocsQuery(), ValueType.GEOPOINT, iw -> {
119+
for (int i = 0; i < 10; i++) {
120+
Document document = new Document();
121+
document.add(new LatLonDocValuesField("field", 10, 10));
122+
iw.addDocument(document);
123+
}
124+
}, count -> assertEquals(10L, count.getValue()));
125+
}
126+
127+
public void testDoubleField() throws IOException {
128+
testCase(new MatchAllDocsQuery(), ValueType.DOUBLE, iw -> {
129+
for (int i = 0; i < 15; i++) {
130+
Document document = new Document();
131+
document.add(new DoubleDocValuesField(FIELD_NAME, 23D));
132+
iw.addDocument(document);
133+
}
134+
}, count -> assertEquals(15L, count.getValue()));
135+
}
136+
137+
public void testKeyWordField() throws IOException {
138+
testCase(new MatchAllDocsQuery(), ValueType.STRING, iw -> {
139+
for (int i = 0; i < 20; i++) {
140+
Document document = new Document();
141+
document.add(new SortedSetDocValuesField(FIELD_NAME, new BytesRef("stringValue")));
142+
document.add(new SortedSetDocValuesField(FIELD_NAME, new BytesRef("string11Value")));
143+
iw.addDocument(document);
144+
}
145+
}, count -> assertEquals(40L, count.getValue()));
146+
}
147+
113148
public void testNoDocs() throws IOException {
114149
for (ValueType valueType : ValueType.values()) {
115150
testCase(new MatchAllDocsQuery(), valueType, iw -> {
@@ -239,7 +274,7 @@ public void testRangeFieldValues() throws IOException {
239274
public void testValueScriptNumber() throws IOException {
240275
ValueCountAggregationBuilder aggregationBuilder = new ValueCountAggregationBuilder("name")
241276
.field(FIELD_NAME)
242-
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
277+
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, NUMBER_VALUE_SCRIPT, Collections.emptyMap()));
243278

244279
MappedFieldType fieldType = createMappedFieldType(ValueType.NUMERIC);
245280
fieldType.setName(FIELD_NAME);
@@ -288,7 +323,7 @@ public void testSingleScriptNumber() throws IOException {
288323
public void testValueScriptString() throws IOException {
289324
ValueCountAggregationBuilder aggregationBuilder = new ValueCountAggregationBuilder("name")
290325
.field(FIELD_NAME)
291-
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, VALUE_SCRIPT, Collections.emptyMap()));
326+
.script(new Script(ScriptType.INLINE, MockScriptEngine.NAME, STRING_VALUE_SCRIPT, Collections.emptyMap()));
292327

293328
MappedFieldType fieldType = createMappedFieldType(ValueType.STRING);
294329
fieldType.setName(FIELD_NAME);

0 commit comments

Comments
 (0)