Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DATAREDIS-814 - Create zset index for sorting and range query #471

Open
wants to merge 5 commits into
base: 2.7.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions src/main/java/org/springframework/data/redis/core/IndexWriter.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import org.springframework.data.redis.core.convert.RedisConverter;
import org.springframework.data.redis.core.convert.RemoveIndexedData;
import org.springframework.data.redis.core.convert.SimpleIndexedPropertyValue;
import org.springframework.data.redis.core.convert.SortingIndexedPropertyValue;
import org.springframework.data.redis.util.ByteUtils;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
Expand All @@ -39,6 +40,7 @@
*
* @author Christoph Strobl
* @author Rob Winch
* @author Yan Ma
* @since 1.7
*/
class IndexWriter {
Expand Down Expand Up @@ -106,7 +108,7 @@ private void createOrUpdateIndexes(Object key, @Nullable Iterable<IndexedData> i

if (indexValues.iterator().hasNext()) {
IndexedData data = indexValues.iterator().next();
if (data != null) {
if (data != null && data.getKeyspace() != null) {
removeKeyFromIndexes(data.getKeyspace(), binKey);
}
}
Expand Down Expand Up @@ -179,6 +181,8 @@ protected void removeKeyFromExistingIndexes(byte[] key, IndexedData indexedData)

if (indexedData instanceof GeoIndexedPropertyValue) {
connection.geoRemove(existingKey, key);
} else if(indexedData instanceof SortingIndexedPropertyValue){
connection.zRem(existingKey, key);
} else {
connection.sRem(existingKey, key);
}
Expand Down Expand Up @@ -222,7 +226,19 @@ protected void addKeyToIndex(byte[] key, IndexedData indexedData) {

// keep track of indexes used for the object
connection.sAdd(ByteUtils.concatAll(toBytes(indexedData.getKeyspace() + ":"), key, toBytes(":idx")), indexKey);
} else if (indexedData instanceof GeoIndexedPropertyValue) {
} else if(indexedData instanceof SortingIndexedPropertyValue ) {
SortingIndexedPropertyValue sortingIndexedData = (SortingIndexedPropertyValue) indexedData;
String indexName = sortingIndexedData.getIndexName();
if(indexName == null) return;
Double score = sortingIndexedData.getScore();
if(score == null) return;

byte[] indexKey = toBytes(indexedData.getKeyspace() + ":" + indexName);
connection.zAdd(indexKey , score, key);

// keep track of indexes used for the object
connection.sAdd(ByteUtils.concatAll(toBytes(indexedData.getKeyspace() + ":"), key, toBytes(":idx")), indexKey);
} else if (indexedData instanceof GeoIndexedPropertyValue) {

GeoIndexedPropertyValue geoIndexedData = ((GeoIndexedPropertyValue) indexedData);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,18 @@
*/
package org.springframework.data.redis.core;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.data.geo.Circle;
import org.springframework.data.geo.GeoResult;
Expand All @@ -30,7 +35,9 @@
import org.springframework.data.keyvalue.core.QueryEngine;
import org.springframework.data.keyvalue.core.SortAccessor;
import org.springframework.data.keyvalue.core.query.KeyValueQuery;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisGeoCommands.GeoLocation;
import org.springframework.data.redis.connection.RedisZSetCommands.Range;
import org.springframework.data.redis.core.convert.GeoIndexedPropertyValue;
import org.springframework.data.redis.core.convert.RedisData;
import org.springframework.data.redis.repository.query.RedisOperationChain;
Expand All @@ -45,6 +52,7 @@
*
* @author Christoph Strobl
* @author Mark Paluch
* @author Yan Ma
* @since 1.7
*/
class RedisQueryEngine extends QueryEngine<RedisKeyValueAdapter, RedisOperationChain, Comparator<?>> {
Expand Down Expand Up @@ -78,7 +86,8 @@ public <T> Collection<T> execute(RedisOperationChain criteria, Comparator<?> sor
String keyspace, Class<T> type) {

if (criteria == null
|| (CollectionUtils.isEmpty(criteria.getOrSismember()) && CollectionUtils.isEmpty(criteria.getSismember()))
|| (CollectionUtils.isEmpty(criteria.getOrSismember())
&& CollectionUtils.isEmpty(criteria.getSismember()))
&& criteria.getNear() == null) {
return (Collection<T>) getAdapter().getAllOf(keyspace, offset, rows);
}
Expand All @@ -87,11 +96,11 @@ public <T> Collection<T> execute(RedisOperationChain criteria, Comparator<?> sor

List<byte[]> allKeys = new ArrayList<>();
if (!criteria.getSismember().isEmpty()) {
allKeys.addAll(connection.sInter(keys(keyspace + ":", criteria.getSismember())));
allKeys.addAll(getKeysFromIsMembers(connection, keyspace + ":", criteria.getSismember()));
}

if (!criteria.getOrSismember().isEmpty()) {
allKeys.addAll(connection.sUnion(keys(keyspace + ":", criteria.getOrSismember())));
allKeys.addAll(getKeysFromOrMembers(connection, keyspace + ":", criteria.getOrSismember()));
}

if (criteria.getNear() != null) {
Expand Down Expand Up @@ -142,6 +151,166 @@ public <T> Collection<T> execute(RedisOperationChain criteria, Comparator<?> sor
return result;
}


private Collection<? extends byte[]> getKeysFromIsMembers(RedisConnection connection, String prefix,
Set<PathAndValue> members) {

// get simple types
Set<PathAndValue> simpleQueries = new HashSet<PathAndValue>();
// get range types
Set<PathAndValue> rangeQueries = new HashSet<PathAndValue>();
for (PathAndValue curr : members) {
if (curr.getFirstValue() instanceof Range) {
rangeQueries.add(curr);
} else {
simpleQueries.add(curr);
}
}

Set<byte[]> sInter = new HashSet<byte[]>();
// To limit the range query size should not exceeds 1.
if(rangeQueries.size() > 1) {
return sInter;
}

if (!simpleQueries.isEmpty()) {
sInter = connection.sInter(keys(prefix, simpleQueries));
}

if (!simpleQueries.isEmpty() && sInter.isEmpty()) {
// we do have something in simple queries but nothing found in the intersections.
// no need of further checks. just return the empty set
return sInter;
}

boolean rangeQueryOnly = simpleQueries.isEmpty();
for (PathAndValue pathAndValue : rangeQueries) {// 0 or 1 loop only
byte[] keyInByte = getAdapter().getConverter().getConversionService().convert(prefix + pathAndValue.getPath(),
byte[].class);
Set<byte[]> zRangeByScore = connection.zRangeByScore(keyInByte, (Range) pathAndValue.getFirstValue());
if(rangeQueryOnly){
// no simple query but range query only.
sInter.addAll(zRangeByScore);
} else {
if (sInter.isEmpty()) {
// in case we support multiple range queries later this could be a quick return
// no more simple query overlapping with range query any more
// return the empty set
return sInter;
} else {
// remain intersections only
Iterator<byte[]> itSimpleQuery = sInter.iterator();
while (itSimpleQuery.hasNext()) {
Iterator<byte[]> itTarget = zRangeByScore.iterator();
byte[] source = itSimpleQuery.next();
boolean isContained = false;
while (itTarget.hasNext()) {
byte[] target = itTarget.next();
if (Arrays.equals(source, target)) {
isContained = true;
break;
}
}
if (!isContained) {
itSimpleQuery.remove();
}
}
}
}
}

return sInter;
}

private Collection<? extends byte[]> getKeysFromOrMembers(RedisConnection connection, String prefix,
Set<PathAndValue> members) {

// get simple types
Set<PathAndValue> simpleQueries = new HashSet<PathAndValue>();
// get range types
Set<PathAndValue> rangeQueries = new HashSet<PathAndValue>();

for (PathAndValue curr : members) {
if (curr.getFirstValue() instanceof Range) {
rangeQueries.add(curr);
} else {
simpleQueries.add(curr);
}
}

Set<byte[]> sUnion = new HashSet<byte[]>();
// To limit the range query size should not exceeds 1.
if(rangeQueries.size() > 1) return sUnion;

Set<byte[]> simpleUnion = connection.sUnion(keys(prefix, simpleQueries));
Set<ByteBuffer> tmpSet = new HashSet<ByteBuffer>();
for (PathAndValue pathAndValue : rangeQueries) {// 0 or 1 loop only
byte[] keyInByte = getAdapter().getConverter().getConversionService()
.convert(prefix + pathAndValue.getPath(), byte[].class);
Set<byte[]> zRangeByScore = connection.zRangeByScore(keyInByte, (Range) pathAndValue.getFirstValue());
// To merge range query with simple query union
// O(n) + O(m), n = the number fo range query results, m = the number simple query union
for(byte[] entry : zRangeByScore){
tmpSet.add(ByteBuffer.wrap(entry));
}
}
for(byte[] entry: simpleUnion){
tmpSet.add(ByteBuffer.wrap(entry));
}
for(ByteBuffer bb : tmpSet){
sUnion.add(bb.array());
}
// this method time complexity is O(n x m)
// Set<byte[]> extra = new HashSet<byte[]>();
// Iterator<byte[]> itUnion = (Iterator<byte[]>) sUnion.iterator();
// while (itUnion.hasNext()) {
// Iterator<byte[]> itRange = (Iterator<byte[]>) zRangeByScore.iterator();
// byte[] source = itUnion.next();
// boolean isContained = false;
// while (itRange.hasNext()) {
// byte[] target = itRange.next();
// if (Arrays.equals(source, target)) {
// isContained = true;
// break;
// }
// }
// if (!isContained) {
// extra.add(source);
// }
// }
return sUnion;
}
// private Collection<? extends byte[]> getKeysFromOrMembers(RedisConnection connection, String prefix,
// Set<Set<PathAndValue>> members) {
//
// Set<byte[]> sUnion = new HashSet<byte[]>();
// for (Set<PathAndValue> isMemberSet : members) {
// Collection<? extends byte[]> keysFromIsMembers = getKeysFromIsMembers(connection, prefix, isMemberSet);
// if (sUnion.isEmpty()) {
// sUnion.addAll(keysFromIsMembers);
// } else {
// // merge
// Iterator<byte[]> it = (Iterator<byte[]>) keysFromIsMembers.iterator();
// while (it.hasNext()) {
// Iterator<byte[]> itTarget = (Iterator<byte[]>) sUnion.iterator();
// byte[] source = it.next();
// boolean isContained = false;
// while (itTarget.hasNext()) {
// byte[] target = itTarget.next();
// if (Arrays.equals(source, target)) {
// isContained = true;
// break;
// }
// }
// if (!isContained) {
// sUnion.add(source);
// }
// }
// }
// }
// return sUnion;
// }

/*
* (non-Javadoc)
* @see org.springframework.data.keyvalue.core.QueryEngine#execute(java.lang.Object, java.lang.Object, int, int, java.lang.String)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,11 @@
package org.springframework.data.redis.core.convert;

import org.springframework.data.geo.Point;
import org.springframework.data.redis.core.index.CompositeSortingIndexDefinition;
import org.springframework.data.redis.core.index.GeoIndexDefinition;
import org.springframework.data.redis.core.index.IndexDefinition;
import org.springframework.data.redis.core.index.SimpleIndexDefinition;
import org.springframework.data.redis.core.index.SortingIndexDefinition;
import org.springframework.lang.Nullable;

/**
Expand All @@ -38,14 +40,37 @@ IndexedDataFactory getIndexedDataFactory(IndexDefinition definition) {
return new SimpleIndexedPropertyValueFactory((SimpleIndexDefinition) definition);
} else if (definition instanceof GeoIndexDefinition) {
return new GeoIndexedPropertyValueFactory(((GeoIndexDefinition) definition));
}
} else if (definition instanceof SortingIndexDefinition){
return new SortingIndexedPropertyValueFactory(((SortingIndexDefinition) definition));
}
return null;
}

static interface IndexedDataFactory {
IndexedData createIndexedDataFor(Object value);
}

static class SortingIndexedPropertyValueFactory implements IndexedDataFactory {
final SortingIndexDefinition indexDefinition;

public SortingIndexedPropertyValueFactory(SortingIndexDefinition indexDefinition) {
this.indexDefinition = indexDefinition;
}

@Override
public IndexedData createIndexedDataFor(Object value) {
if (indexDefinition instanceof CompositeSortingIndexDefinition) {
CompositeSortingIndexDefinition csid = (CompositeSortingIndexDefinition) indexDefinition;
return new SortingIndexedPropertyValue(indexDefinition.getKeyspace(), csid.getIndexName(value),
csid.getIndexValue(value));
} else {
return new SortingIndexedPropertyValue(indexDefinition.getKeyspace(), indexDefinition.getIndexName(),
indexDefinition.valueTransformer().convert(value));
}
}

}

/**
* @author Christoph Strobl
* @since 1.8
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package org.springframework.data.redis.core.convert;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Map;
Expand Down Expand Up @@ -194,9 +195,38 @@ private TypeInformation<?> updateTypeHintForActualValue(TypeInformation<?> typeH
}

});


// customized code for top level index
indexes.addAll(resolveCompositeIndexes(keyspace, path, typeInformation, value));

return indexes;
}

private Collection<? extends IndexedData> resolveCompositeIndexes(String keyspace, String path,
TypeInformation<?> typeInformation, Object value) {

Set<IndexedData> data = new LinkedHashSet<IndexedData>();
if (indexConfiguration.hasIndexFor(keyspace, path)) {
IndexingContext context = new IndexingContext(keyspace, path, typeInformation);

for (IndexDefinition indexDefinition : indexConfiguration.getIndexDefinitionsFor(keyspace, path)) {
if (!verifyConditions(indexDefinition.getConditions(), value, context)) {
continue;
}
Object transformedValue = indexDefinition.valueTransformer().convert(value);

IndexedData indexedData = null;
if (transformedValue == null) {
indexedData = new RemoveIndexedData(indexedData);
} else {
indexedData = indexedDataFactoryProvider.getIndexedDataFactory(indexDefinition).createIndexedDataFor(value);
}
data.add(indexedData);
}
}

return data;
}

protected Set<IndexedData> resolveIndex(String keyspace, String propertyPath,
@Nullable PersistentProperty<?> property, @Nullable Object value) {
Expand Down
Loading