DATAES-2 Applied spring-data formatting to all sources
This commit is contained in:
@@ -15,38 +15,37 @@
|
||||
*/
|
||||
package org.springframework.data.elasticsearch;
|
||||
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* ElasticsearchException
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
public class ElasticsearchException extends RuntimeException{
|
||||
public class ElasticsearchException extends RuntimeException {
|
||||
|
||||
private Map<String, String> failedDocuments;
|
||||
private Map<String, String> failedDocuments;
|
||||
|
||||
public ElasticsearchException(String message) {
|
||||
super(message);
|
||||
}
|
||||
public ElasticsearchException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public ElasticsearchException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
public ElasticsearchException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public ElasticsearchException(String message, Throwable cause, Map<String, String> failedDocuments) {
|
||||
super(message, cause);
|
||||
this.failedDocuments = failedDocuments;
|
||||
}
|
||||
public ElasticsearchException(String message, Throwable cause, Map<String, String> failedDocuments) {
|
||||
super(message, cause);
|
||||
this.failedDocuments = failedDocuments;
|
||||
}
|
||||
|
||||
public ElasticsearchException(String message, Map<String, String> failedDocuments) {
|
||||
super(message);
|
||||
this.failedDocuments = failedDocuments;
|
||||
}
|
||||
public ElasticsearchException(String message, Map<String, String> failedDocuments) {
|
||||
super(message);
|
||||
this.failedDocuments = failedDocuments;
|
||||
}
|
||||
|
||||
public Map<String, String> getFailedDocuments() {
|
||||
return failedDocuments;
|
||||
}
|
||||
public Map<String, String> getFailedDocuments() {
|
||||
return failedDocuments;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,14 +15,13 @@
|
||||
*/
|
||||
package org.springframework.data.elasticsearch.annotations;
|
||||
|
||||
|
||||
import org.springframework.data.annotation.Persistent;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* Document
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
@@ -33,10 +32,15 @@ import java.lang.annotation.*;
|
||||
@Target({ ElementType.TYPE })
|
||||
public @interface Document {
|
||||
|
||||
String indexName();
|
||||
String type() default "";
|
||||
short shards() default 1;
|
||||
short replicas() default 5;
|
||||
String refreshInterval() default "1s";
|
||||
String indexStoreType() default "fs";
|
||||
String indexName();
|
||||
|
||||
String type() default "";
|
||||
|
||||
short shards() default 1;
|
||||
|
||||
short replicas() default 5;
|
||||
|
||||
String refreshInterval() default "1s";
|
||||
|
||||
String indexStoreType() default "fs";
|
||||
}
|
||||
|
||||
@@ -17,7 +17,6 @@ package org.springframework.data.elasticsearch.annotations;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
|
||||
/**
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
@@ -27,10 +26,14 @@ import java.lang.annotation.*;
|
||||
@Documented
|
||||
public @interface Field {
|
||||
|
||||
String type() default "";
|
||||
String index() default "";
|
||||
boolean store() default false;
|
||||
String searchAnalyzer() default "";
|
||||
String indexAnalyzer() default "";
|
||||
String type() default "";
|
||||
|
||||
String index() default "";
|
||||
|
||||
boolean store() default false;
|
||||
|
||||
String searchAnalyzer() default "";
|
||||
|
||||
String indexAnalyzer() default "";
|
||||
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* Query
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
@@ -29,18 +29,18 @@ import java.lang.annotation.*;
|
||||
@Documented
|
||||
public @interface Query {
|
||||
|
||||
/**
|
||||
* Elasticsearch query to be used when executing query. May contain placeholders eg. ?0
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
String value() default "";
|
||||
/**
|
||||
* Elasticsearch query to be used when executing query. May contain placeholders eg. ?0
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
String value() default "";
|
||||
|
||||
/**
|
||||
* Named Query Named looked up by repository.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
String name() default "";
|
||||
/**
|
||||
* Named Query Named looked up by repository.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
String name() default "";
|
||||
|
||||
}
|
||||
|
||||
@@ -27,72 +27,72 @@ import org.springframework.beans.factory.InitializingBean;
|
||||
import static org.elasticsearch.node.NodeBuilder.nodeBuilder;
|
||||
|
||||
/**
|
||||
* NodeClientFactoryBean
|
||||
*
|
||||
* NodeClientFactoryBean
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
|
||||
public class NodeClientFactoryBean implements FactoryBean<NodeClient>, InitializingBean, DisposableBean {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(NodeClientFactoryBean.class);
|
||||
private boolean local;
|
||||
private boolean enableHttp;
|
||||
private String clusterName;
|
||||
private NodeClient nodeClient;
|
||||
private static final Logger logger = LoggerFactory.getLogger(NodeClientFactoryBean.class);
|
||||
private boolean local;
|
||||
private boolean enableHttp;
|
||||
private String clusterName;
|
||||
private NodeClient nodeClient;
|
||||
|
||||
NodeClientFactoryBean() {
|
||||
}
|
||||
NodeClientFactoryBean() {
|
||||
}
|
||||
|
||||
public NodeClientFactoryBean(boolean local) {
|
||||
this.local = local;
|
||||
}
|
||||
public NodeClientFactoryBean(boolean local) {
|
||||
this.local = local;
|
||||
}
|
||||
|
||||
@Override
|
||||
public NodeClient getObject() throws Exception {
|
||||
return nodeClient;
|
||||
}
|
||||
@Override
|
||||
public NodeClient getObject() throws Exception {
|
||||
return nodeClient;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<? extends Client> getObjectType() {
|
||||
return NodeClient.class;
|
||||
}
|
||||
@Override
|
||||
public Class<? extends Client> getObjectType() {
|
||||
return NodeClient.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSingleton() {
|
||||
return true;
|
||||
}
|
||||
@Override
|
||||
public boolean isSingleton() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterPropertiesSet() throws Exception {
|
||||
ImmutableSettings.Builder settings = ImmutableSettings.settingsBuilder()
|
||||
.put("http.enabled", String.valueOf(this.enableHttp));
|
||||
@Override
|
||||
public void afterPropertiesSet() throws Exception {
|
||||
ImmutableSettings.Builder settings = ImmutableSettings.settingsBuilder().put("http.enabled",
|
||||
String.valueOf(this.enableHttp));
|
||||
|
||||
nodeClient = (NodeClient) nodeBuilder().settings(settings)
|
||||
.clusterName(this.clusterName).local(this.local).node().client();
|
||||
}
|
||||
nodeClient = (NodeClient) nodeBuilder().settings(settings).clusterName(this.clusterName).local(this.local).node()
|
||||
.client();
|
||||
}
|
||||
|
||||
public void setLocal(boolean local) {
|
||||
this.local = local;
|
||||
}
|
||||
public void setLocal(boolean local) {
|
||||
this.local = local;
|
||||
}
|
||||
|
||||
public void setEnableHttp(boolean enableHttp) {
|
||||
this.enableHttp = enableHttp;
|
||||
}
|
||||
public void setEnableHttp(boolean enableHttp) {
|
||||
this.enableHttp = enableHttp;
|
||||
}
|
||||
|
||||
public void setClusterName(String clusterName) {
|
||||
this.clusterName = clusterName;
|
||||
}
|
||||
public void setClusterName(String clusterName) {
|
||||
this.clusterName = clusterName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() throws Exception {
|
||||
try {
|
||||
logger.info("Closing elasticSearch client");
|
||||
if (nodeClient != null) {
|
||||
nodeClient.close();
|
||||
}
|
||||
} catch (final Exception e) {
|
||||
logger.error("Error closing ElasticSearch client: ", e);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public void destroy() throws Exception {
|
||||
try {
|
||||
logger.info("Closing elasticSearch client");
|
||||
if (nodeClient != null) {
|
||||
nodeClient.close();
|
||||
}
|
||||
} catch (final Exception e) {
|
||||
logger.error("Error closing ElasticSearch client: ", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,79 +32,78 @@ import static org.apache.commons.lang.StringUtils.substringBefore;
|
||||
import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder;
|
||||
|
||||
/**
|
||||
* TransportClientFactoryBean
|
||||
*
|
||||
* TransportClientFactoryBean
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
|
||||
public class TransportClientFactoryBean implements FactoryBean<TransportClient>, InitializingBean, DisposableBean {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(TransportClientFactoryBean.class);
|
||||
private String[] clusterNodes;
|
||||
private TransportClient client;
|
||||
private Properties properties;
|
||||
static final String COLON = ":";
|
||||
private static final Logger logger = LoggerFactory.getLogger(TransportClientFactoryBean.class);
|
||||
private String[] clusterNodes;
|
||||
private TransportClient client;
|
||||
private Properties properties;
|
||||
static final String COLON = ":";
|
||||
|
||||
@Override
|
||||
public void destroy() throws Exception {
|
||||
try {
|
||||
logger.info("Closing elasticSearch client");
|
||||
if (client != null) {
|
||||
client.close();
|
||||
}
|
||||
} catch (final Exception e) {
|
||||
logger.error("Error closing ElasticSearch client: ", e);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public void destroy() throws Exception {
|
||||
try {
|
||||
logger.info("Closing elasticSearch client");
|
||||
if (client != null) {
|
||||
client.close();
|
||||
}
|
||||
} catch (final Exception e) {
|
||||
logger.error("Error closing ElasticSearch client: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public TransportClient getObject() throws Exception {
|
||||
return client;
|
||||
}
|
||||
@Override
|
||||
public TransportClient getObject() throws Exception {
|
||||
return client;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<TransportClient> getObjectType() {
|
||||
return TransportClient.class;
|
||||
}
|
||||
@Override
|
||||
public Class<TransportClient> getObjectType() {
|
||||
return TransportClient.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSingleton() {
|
||||
return false;
|
||||
}
|
||||
@Override
|
||||
public boolean isSingleton() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterPropertiesSet() throws Exception {
|
||||
buildClient();
|
||||
}
|
||||
@Override
|
||||
public void afterPropertiesSet() throws Exception {
|
||||
buildClient();
|
||||
}
|
||||
|
||||
protected void buildClient() throws Exception {
|
||||
client = new TransportClient(settings());
|
||||
Assert.notEmpty(clusterNodes,"[Assertion failed] clusterNodes settings missing.");
|
||||
for (String clusterNode : clusterNodes) {
|
||||
String hostName = substringBefore(clusterNode, COLON);
|
||||
String port = substringAfter(clusterNode, COLON);
|
||||
Assert.hasText(hostName,"[Assertion failed] missing host name in 'clusterNodes'");
|
||||
Assert.hasText(port,"[Assertion failed] missing port in 'clusterNodes'");
|
||||
logger.info("adding transport node : " + clusterNode);
|
||||
client.addTransportAddress(new InetSocketTransportAddress(hostName, Integer.valueOf(port)));
|
||||
}
|
||||
client.connectedNodes();
|
||||
}
|
||||
protected void buildClient() throws Exception {
|
||||
client = new TransportClient(settings());
|
||||
Assert.notEmpty(clusterNodes, "[Assertion failed] clusterNodes settings missing.");
|
||||
for (String clusterNode : clusterNodes) {
|
||||
String hostName = substringBefore(clusterNode, COLON);
|
||||
String port = substringAfter(clusterNode, COLON);
|
||||
Assert.hasText(hostName, "[Assertion failed] missing host name in 'clusterNodes'");
|
||||
Assert.hasText(port, "[Assertion failed] missing port in 'clusterNodes'");
|
||||
logger.info("adding transport node : " + clusterNode);
|
||||
client.addTransportAddress(new InetSocketTransportAddress(hostName, Integer.valueOf(port)));
|
||||
}
|
||||
client.connectedNodes();
|
||||
}
|
||||
|
||||
private Settings settings(){
|
||||
if(properties != null){
|
||||
return settingsBuilder().put(properties).build();
|
||||
}
|
||||
return settingsBuilder()
|
||||
.put("client.transport.sniff",true).build();
|
||||
}
|
||||
private Settings settings() {
|
||||
if (properties != null) {
|
||||
return settingsBuilder().put(properties).build();
|
||||
}
|
||||
return settingsBuilder().put("client.transport.sniff", true).build();
|
||||
}
|
||||
|
||||
public void setClusterNodes(String[] clusterNodes) {
|
||||
this.clusterNodes = clusterNodes;
|
||||
}
|
||||
public void setClusterNodes(String[] clusterNodes) {
|
||||
this.clusterNodes = clusterNodes;
|
||||
}
|
||||
|
||||
public void setProperties(Properties properties) {
|
||||
this.properties = properties;
|
||||
}
|
||||
public void setProperties(Properties properties) {
|
||||
this.properties = properties;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,21 +21,21 @@ import org.springframework.data.repository.config.RepositoryBeanDefinitionParser
|
||||
import org.springframework.data.repository.config.RepositoryConfigurationExtension;
|
||||
|
||||
/**
|
||||
* ElasticsearchNamespaceHandler
|
||||
*
|
||||
* ElasticsearchNamespaceHandler
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
|
||||
public class ElasticsearchNamespaceHandler extends NamespaceHandlerSupport{
|
||||
public class ElasticsearchNamespaceHandler extends NamespaceHandlerSupport {
|
||||
|
||||
@Override
|
||||
public void init() {
|
||||
RepositoryConfigurationExtension extension = new ElasticsearchRepositoryConfigExtension();
|
||||
@Override
|
||||
public void init() {
|
||||
RepositoryConfigurationExtension extension = new ElasticsearchRepositoryConfigExtension();
|
||||
RepositoryBeanDefinitionParser parser = new RepositoryBeanDefinitionParser(extension);
|
||||
|
||||
registerBeanDefinitionParser("repositories", parser);
|
||||
registerBeanDefinitionParser("node-client", new NodeClientBeanDefinitionParser());
|
||||
registerBeanDefinitionParser("transport-client", new TransportClientBeanDefinitionParser());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,31 +25,30 @@ import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* NodeClientBeanDefinitionParser
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
|
||||
public class NodeClientBeanDefinitionParser extends AbstractBeanDefinitionParser {
|
||||
|
||||
@Override
|
||||
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
|
||||
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(NodeClientFactoryBean.class);
|
||||
setLocalSettings(element,builder);
|
||||
return getSourcedBeanDefinition(builder, element, parserContext);
|
||||
}
|
||||
@Override
|
||||
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
|
||||
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(NodeClientFactoryBean.class);
|
||||
setLocalSettings(element, builder);
|
||||
return getSourcedBeanDefinition(builder, element, parserContext);
|
||||
}
|
||||
|
||||
private void setLocalSettings(Element element, BeanDefinitionBuilder builder) {
|
||||
builder.addPropertyValue("local", Boolean.valueOf(element.getAttribute("local")));
|
||||
builder.addPropertyValue("clusterName", element.getAttribute("cluster-name"));
|
||||
builder.addPropertyValue("enableHttp",Boolean.valueOf(element.getAttribute("http-enabled")));
|
||||
}
|
||||
private void setLocalSettings(Element element, BeanDefinitionBuilder builder) {
|
||||
builder.addPropertyValue("local", Boolean.valueOf(element.getAttribute("local")));
|
||||
builder.addPropertyValue("clusterName", element.getAttribute("cluster-name"));
|
||||
builder.addPropertyValue("enableHttp", Boolean.valueOf(element.getAttribute("http-enabled")));
|
||||
}
|
||||
|
||||
|
||||
private AbstractBeanDefinition getSourcedBeanDefinition(BeanDefinitionBuilder builder, Element source,
|
||||
ParserContext context) {
|
||||
AbstractBeanDefinition definition = builder.getBeanDefinition();
|
||||
definition.setSource(context.extractSource(source));
|
||||
return definition;
|
||||
}
|
||||
private AbstractBeanDefinition getSourcedBeanDefinition(BeanDefinitionBuilder builder, Element source,
|
||||
ParserContext context) {
|
||||
AbstractBeanDefinition definition = builder.getBeanDefinition();
|
||||
definition.setSource(context.extractSource(source));
|
||||
return definition;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,32 +23,33 @@ import org.springframework.data.elasticsearch.client.TransportClientFactoryBean;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
import static org.apache.commons.lang.StringUtils.split;
|
||||
|
||||
/**
|
||||
* TransportClientBeanDefinitionParser
|
||||
*
|
||||
* TransportClientBeanDefinitionParser
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
|
||||
public class TransportClientBeanDefinitionParser extends AbstractBeanDefinitionParser {
|
||||
|
||||
private static final String SEPARATOR_CHARS = ",";
|
||||
private static final String SEPARATOR_CHARS = ",";
|
||||
|
||||
@Override
|
||||
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
|
||||
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(TransportClientFactoryBean.class);
|
||||
setClusterNodes(element, builder);
|
||||
return getSourcedBeanDefinition(builder,element, parserContext);
|
||||
}
|
||||
@Override
|
||||
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
|
||||
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(TransportClientFactoryBean.class);
|
||||
setClusterNodes(element, builder);
|
||||
return getSourcedBeanDefinition(builder, element, parserContext);
|
||||
}
|
||||
|
||||
private void setClusterNodes(Element element, BeanDefinitionBuilder builder){
|
||||
builder.addPropertyValue("clusterNodes", split(element.getAttribute("cluster-nodes"), SEPARATOR_CHARS));
|
||||
}
|
||||
private void setClusterNodes(Element element, BeanDefinitionBuilder builder) {
|
||||
builder.addPropertyValue("clusterNodes", split(element.getAttribute("cluster-nodes"), SEPARATOR_CHARS));
|
||||
}
|
||||
|
||||
private AbstractBeanDefinition getSourcedBeanDefinition(BeanDefinitionBuilder builder, Element source,
|
||||
ParserContext context) {
|
||||
AbstractBeanDefinition definition = builder.getBeanDefinition();
|
||||
definition.setSource(context.extractSource(source));
|
||||
return definition;
|
||||
}
|
||||
private AbstractBeanDefinition getSourcedBeanDefinition(BeanDefinitionBuilder builder, Element source,
|
||||
ParserContext context) {
|
||||
AbstractBeanDefinition definition = builder.getBeanDefinition();
|
||||
definition.setSource(context.extractSource(source));
|
||||
return definition;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,106 +29,109 @@ import static org.springframework.data.elasticsearch.core.query.Criteria.Operati
|
||||
|
||||
/**
|
||||
* CriteriaQueryProcessor
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
class CriteriaQueryProcessor {
|
||||
|
||||
QueryBuilder createQueryFromCriteria(Criteria criteria) {
|
||||
BoolQueryBuilder query = boolQuery();
|
||||
|
||||
QueryBuilder createQueryFromCriteria(Criteria criteria) {
|
||||
BoolQueryBuilder query = boolQuery();
|
||||
ListIterator<Criteria> chainIterator = criteria.getCriteriaChain().listIterator();
|
||||
while (chainIterator.hasNext()) {
|
||||
Criteria chainedCriteria = chainIterator.next();
|
||||
if (chainedCriteria.isOr()) {
|
||||
query.should(createQueryFragmentForCriteria(chainedCriteria));
|
||||
} else if (chainedCriteria.isNegating()) {
|
||||
query.mustNot(createQueryFragmentForCriteria(chainedCriteria));
|
||||
} else {
|
||||
query.must(createQueryFragmentForCriteria(chainedCriteria));
|
||||
}
|
||||
}
|
||||
return query;
|
||||
}
|
||||
|
||||
ListIterator<Criteria> chainIterator = criteria.getCriteriaChain().listIterator();
|
||||
while (chainIterator.hasNext()) {
|
||||
Criteria chainedCriteria = chainIterator.next();
|
||||
if(chainedCriteria.isOr()){
|
||||
query.should(createQueryFragmentForCriteria(chainedCriteria));
|
||||
}else if(chainedCriteria.isNegating()){
|
||||
query.mustNot(createQueryFragmentForCriteria(chainedCriteria));
|
||||
}else{
|
||||
query.must(createQueryFragmentForCriteria(chainedCriteria));
|
||||
}
|
||||
}
|
||||
return query;
|
||||
}
|
||||
private QueryBuilder createQueryFragmentForCriteria(Criteria chainedCriteria) {
|
||||
Iterator<Criteria.CriteriaEntry> it = chainedCriteria.getCriteriaEntries().iterator();
|
||||
boolean singeEntryCriteria = (chainedCriteria.getCriteriaEntries().size() == 1);
|
||||
|
||||
String fieldName = chainedCriteria.getField().getName();
|
||||
Assert.notNull(fieldName, "Unknown field");
|
||||
QueryBuilder query = null;
|
||||
|
||||
private QueryBuilder createQueryFragmentForCriteria(Criteria chainedCriteria) {
|
||||
Iterator<Criteria.CriteriaEntry> it = chainedCriteria.getCriteriaEntries().iterator();
|
||||
boolean singeEntryCriteria = (chainedCriteria.getCriteriaEntries().size() == 1);
|
||||
if (singeEntryCriteria) {
|
||||
Criteria.CriteriaEntry entry = it.next();
|
||||
query = processCriteriaEntry(entry.getKey(), entry.getValue(), fieldName);
|
||||
} else {
|
||||
query = boolQuery();
|
||||
while (it.hasNext()) {
|
||||
Criteria.CriteriaEntry entry = it.next();
|
||||
((BoolQueryBuilder) query).must(processCriteriaEntry(entry.getKey(), entry.getValue(), fieldName));
|
||||
}
|
||||
}
|
||||
|
||||
String fieldName = chainedCriteria.getField().getName();
|
||||
Assert.notNull(fieldName,"Unknown field");
|
||||
QueryBuilder query = null;
|
||||
addBoost(query, chainedCriteria.getBoost());
|
||||
return query;
|
||||
}
|
||||
|
||||
if(singeEntryCriteria){
|
||||
Criteria.CriteriaEntry entry = it.next();
|
||||
query = processCriteriaEntry(entry.getKey(), entry.getValue(), fieldName);
|
||||
}else{
|
||||
query = boolQuery();
|
||||
while (it.hasNext()){
|
||||
Criteria.CriteriaEntry entry = it.next();
|
||||
((BoolQueryBuilder)query).must(processCriteriaEntry(entry.getKey(), entry.getValue(), fieldName));
|
||||
}
|
||||
}
|
||||
private QueryBuilder processCriteriaEntry(OperationKey key, Object value, String fieldName) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
QueryBuilder query = null;
|
||||
|
||||
addBoost(query, chainedCriteria.getBoost());
|
||||
return query;
|
||||
}
|
||||
switch (key) {
|
||||
case EQUALS:
|
||||
query = fieldQuery(fieldName, value);
|
||||
break;
|
||||
case CONTAINS:
|
||||
query = fieldQuery(fieldName, "*" + value + "*").analyzeWildcard(true);
|
||||
break;
|
||||
case STARTS_WITH:
|
||||
query = fieldQuery(fieldName, value + "*").analyzeWildcard(true);
|
||||
break;
|
||||
case ENDS_WITH:
|
||||
query = fieldQuery(fieldName, "*" + value).analyzeWildcard(true);
|
||||
break;
|
||||
case EXPRESSION:
|
||||
query = queryString((String) value).field(fieldName);
|
||||
break;
|
||||
case BETWEEN:
|
||||
Object[] ranges = (Object[]) value;
|
||||
query = rangeQuery(fieldName).from(ranges[0]).to(ranges[1]);
|
||||
break;
|
||||
case FUZZY:
|
||||
query = fuzzyQuery(fieldName, (String) value);
|
||||
break;
|
||||
case IN:
|
||||
query = boolQuery();
|
||||
Iterable<Object> collection = (Iterable<Object>) value;
|
||||
for (Object item : collection) {
|
||||
((BoolQueryBuilder) query).should(fieldQuery(fieldName, item));
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
return query;
|
||||
}
|
||||
|
||||
private QueryBuilder processCriteriaEntry(OperationKey key, Object value, String fieldName) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
QueryBuilder query = null;
|
||||
private QueryBuilder buildNegationQuery(String fieldName, Iterator<Criteria.CriteriaEntry> it) {
|
||||
BoolQueryBuilder notQuery = boolQuery();
|
||||
while (it.hasNext()) {
|
||||
notQuery.mustNot(fieldQuery(fieldName, it.next().getValue()));
|
||||
}
|
||||
return notQuery;
|
||||
}
|
||||
|
||||
switch (key){
|
||||
case EQUALS:
|
||||
query = fieldQuery(fieldName, value); break;
|
||||
case CONTAINS:
|
||||
query = fieldQuery(fieldName,"*" + value + "*").analyzeWildcard(true); break;
|
||||
case STARTS_WITH:
|
||||
query = fieldQuery(fieldName,value +"*").analyzeWildcard(true); break;
|
||||
case ENDS_WITH:
|
||||
query = fieldQuery(fieldName, "*"+value).analyzeWildcard(true); break;
|
||||
case EXPRESSION:
|
||||
query = queryString((String)value).field(fieldName); break;
|
||||
case BETWEEN:
|
||||
Object[] ranges = (Object[]) value;
|
||||
query = rangeQuery(fieldName).from(ranges[0]).to(ranges[1]); break;
|
||||
case FUZZY:
|
||||
query = fuzzyQuery(fieldName, (String) value); break;
|
||||
case IN:
|
||||
query = boolQuery();
|
||||
Iterable<Object> collection = (Iterable<Object>) value;
|
||||
for(Object item : collection){
|
||||
((BoolQueryBuilder) query).should(fieldQuery(fieldName, item));
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
return query;
|
||||
}
|
||||
|
||||
private QueryBuilder buildNegationQuery(String fieldName, Iterator<Criteria.CriteriaEntry> it){
|
||||
BoolQueryBuilder notQuery = boolQuery();
|
||||
while (it.hasNext()){
|
||||
notQuery.mustNot(fieldQuery(fieldName, it.next().getValue()));
|
||||
}
|
||||
return notQuery;
|
||||
}
|
||||
|
||||
private void addBoost(QueryBuilder query, float boost){
|
||||
if(Float.isNaN(boost)){
|
||||
return;
|
||||
}
|
||||
if(query instanceof BoostableQueryBuilder){
|
||||
((BoostableQueryBuilder)query).boost(boost);
|
||||
}
|
||||
|
||||
}
|
||||
private void addBoost(QueryBuilder query, float boost) {
|
||||
if (Float.isNaN(boost)) {
|
||||
return;
|
||||
}
|
||||
if (query instanceof BoostableQueryBuilder) {
|
||||
((BoostableQueryBuilder) query).boost(boost);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -15,7 +15,6 @@
|
||||
*/
|
||||
package org.springframework.data.elasticsearch.core;
|
||||
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter;
|
||||
import org.springframework.data.elasticsearch.core.query.*;
|
||||
@@ -24,235 +23,238 @@ import java.util.List;
|
||||
|
||||
/**
|
||||
* ElasticsearchOperations
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
public interface ElasticsearchOperations {
|
||||
|
||||
/**
|
||||
* @return Converter in use
|
||||
*/
|
||||
ElasticsearchConverter getElasticsearchConverter();
|
||||
|
||||
/**
|
||||
* @return Converter in use
|
||||
*/
|
||||
ElasticsearchConverter getElasticsearchConverter();
|
||||
/**
|
||||
* Create an index for a class
|
||||
*
|
||||
* @param clazz
|
||||
* @param <T>
|
||||
*/
|
||||
<T> boolean createIndex(Class<T> clazz);
|
||||
|
||||
/**
|
||||
* Create an index for a class
|
||||
* @param clazz
|
||||
* @param <T>
|
||||
*/
|
||||
<T> boolean createIndex(Class<T> clazz);
|
||||
/**
|
||||
* Create mapping for a class
|
||||
*
|
||||
* @param clazz
|
||||
* @param <T>
|
||||
*/
|
||||
<T> boolean putMapping(Class<T> clazz);
|
||||
|
||||
/**
|
||||
* Create mapping for a class
|
||||
* @param clazz
|
||||
* @param <T>
|
||||
*/
|
||||
<T> boolean putMapping(Class<T> clazz);
|
||||
/**
|
||||
* Execute the query against elasticsearch and return the first returned object
|
||||
*
|
||||
* @param query
|
||||
* @param clazz
|
||||
* @return the first matching object
|
||||
*/
|
||||
<T> T queryForObject(GetQuery query, Class<T> clazz);
|
||||
|
||||
/**
|
||||
* Execute the query against elasticsearch and return the first returned object
|
||||
*
|
||||
* @param query
|
||||
* @param clazz
|
||||
* @return the first matching object
|
||||
*/
|
||||
<T> T queryForObject(CriteriaQuery query, Class<T> clazz);
|
||||
|
||||
/**
|
||||
* Execute the query against elasticsearch and return the first returned object
|
||||
*
|
||||
* @param query
|
||||
* @param clazz
|
||||
* @return the first matching object
|
||||
*/
|
||||
<T> T queryForObject(GetQuery query, Class<T> clazz);
|
||||
/**
|
||||
* Execute the query against elasticsearch and return the first returned object
|
||||
*
|
||||
* @param query
|
||||
* @param clazz
|
||||
* @return the first matching object
|
||||
*/
|
||||
<T> T queryForObject(StringQuery query, Class<T> clazz);
|
||||
|
||||
/**
|
||||
* Execute the query against elasticsearch and return the first returned object
|
||||
*
|
||||
* @param query
|
||||
* @param clazz
|
||||
* @return the first matching object
|
||||
*/
|
||||
<T> T queryForObject(CriteriaQuery query, Class<T> clazz);
|
||||
/**
|
||||
* Execute the query against elasticsearch and return result as {@link Page}
|
||||
*
|
||||
* @param query
|
||||
* @param clazz
|
||||
* @return
|
||||
*/
|
||||
<T> Page<T> queryForPage(SearchQuery query, Class<T> clazz);
|
||||
|
||||
/**
|
||||
* Execute the query against elasticsearch and return result as {@link Page}
|
||||
*
|
||||
* @param query
|
||||
* @param resultsMapper
|
||||
* @return
|
||||
*/
|
||||
<T> Page<T> queryForPage(SearchQuery query, ResultsMapper<T> resultsMapper);
|
||||
|
||||
/**
|
||||
* Execute the query against elasticsearch and return the first returned object
|
||||
*
|
||||
* @param query
|
||||
* @param clazz
|
||||
* @return the first matching object
|
||||
*/
|
||||
<T> T queryForObject(StringQuery query, Class<T> clazz);
|
||||
/**
|
||||
* Execute the query against elasticsearch and return result as {@link Page}
|
||||
*
|
||||
* @param query
|
||||
* @param clazz
|
||||
* @return
|
||||
*/
|
||||
<T> Page<T> queryForPage(CriteriaQuery query, Class<T> clazz);
|
||||
|
||||
/**
|
||||
* Execute the query against elasticsearch and return result as {@link Page}
|
||||
*
|
||||
* @param query
|
||||
* @param clazz
|
||||
* @return
|
||||
*/
|
||||
<T> Page<T> queryForPage(StringQuery query, Class<T> clazz);
|
||||
|
||||
/**
|
||||
* Execute the query against elasticsearch and return result as {@link Page}
|
||||
*
|
||||
* @param query
|
||||
* @param clazz
|
||||
* @return
|
||||
*/
|
||||
<T> Page<T> queryForPage(SearchQuery query, Class<T> clazz);
|
||||
/**
|
||||
* Execute the criteria query against elasticsearch and return result as {@link List}
|
||||
*
|
||||
* @param query
|
||||
* @param clazz
|
||||
* @param <T>
|
||||
* @return
|
||||
*/
|
||||
<T> List<T> queryForList(CriteriaQuery query, Class<T> clazz);
|
||||
|
||||
/**
|
||||
* Execute the string query against elasticsearch and return result as {@link List}
|
||||
*
|
||||
* @param query
|
||||
* @param clazz
|
||||
* @param <T>
|
||||
* @return
|
||||
*/
|
||||
<T> List<T> queryForList(StringQuery query, Class<T> clazz);
|
||||
|
||||
/**
|
||||
* Execute the query against elasticsearch and return result as {@link Page}
|
||||
*
|
||||
* @param query
|
||||
* @param resultsMapper
|
||||
* @return
|
||||
*/
|
||||
<T> Page<T> queryForPage(SearchQuery query, ResultsMapper<T> resultsMapper);
|
||||
/**
|
||||
* Execute the query against elasticsearch and return ids
|
||||
*
|
||||
* @param query
|
||||
* @return
|
||||
*/
|
||||
<T> List<String> queryForIds(SearchQuery query);
|
||||
|
||||
/**
|
||||
* return number of elements found by for given query
|
||||
*
|
||||
* @param query
|
||||
* @param clazz
|
||||
* @return
|
||||
*/
|
||||
<T> long count(SearchQuery query, Class<T> clazz);
|
||||
|
||||
/**
|
||||
* Execute the query against elasticsearch and return result as {@link Page}
|
||||
*
|
||||
* @param query
|
||||
* @param clazz
|
||||
* @return
|
||||
*/
|
||||
<T> Page<T> queryForPage(CriteriaQuery query, Class<T> clazz);
|
||||
/**
|
||||
* Index an object. Will do save or update
|
||||
*
|
||||
* @param query
|
||||
* @return returns the document id
|
||||
*/
|
||||
String index(IndexQuery query);
|
||||
|
||||
/**
|
||||
* Bulk index all objects. Will do save or update
|
||||
*
|
||||
* @param queries
|
||||
*/
|
||||
void bulkIndex(List<IndexQuery> queries);
|
||||
|
||||
/**
|
||||
* Execute the query against elasticsearch and return result as {@link Page}
|
||||
*
|
||||
* @param query
|
||||
* @param clazz
|
||||
* @return
|
||||
*/
|
||||
<T> Page<T> queryForPage(StringQuery query, Class<T> clazz);
|
||||
/**
|
||||
* Delete the one object with provided id
|
||||
*
|
||||
* @param indexName
|
||||
* @param type
|
||||
* @param id
|
||||
* @return documentId of the document deleted
|
||||
*/
|
||||
String delete(String indexName, String type, String id);
|
||||
|
||||
/**
|
||||
* Execute the criteria query against elasticsearch and return result as {@link List}
|
||||
*
|
||||
* @param query
|
||||
* @param clazz
|
||||
* @param <T>
|
||||
* @return
|
||||
*/
|
||||
<T> List<T> queryForList(CriteriaQuery query, Class<T> clazz);
|
||||
/**
|
||||
* Delete the one object with provided id
|
||||
*
|
||||
* @param clazz
|
||||
* @param id
|
||||
* @return documentId of the document deleted
|
||||
*/
|
||||
<T> String delete(Class<T> clazz, String id);
|
||||
|
||||
/**
|
||||
* Execute the string query against elasticsearch and return result as {@link List}
|
||||
*
|
||||
* @param query
|
||||
* @param clazz
|
||||
* @param <T>
|
||||
* @return
|
||||
*/
|
||||
<T> List<T> queryForList(StringQuery query, Class<T> clazz);
|
||||
/**
|
||||
* Delete all records matching the query
|
||||
*
|
||||
* @param clazz
|
||||
* @param query
|
||||
*/
|
||||
<T> void delete(DeleteQuery query, Class<T> clazz);
|
||||
|
||||
/**
|
||||
* Execute the query against elasticsearch and return ids
|
||||
*
|
||||
* @param query
|
||||
* @return
|
||||
*/
|
||||
<T> List<String> queryForIds(SearchQuery query);
|
||||
/**
|
||||
* Deletes an index for given entity
|
||||
*
|
||||
* @param clazz
|
||||
* @param <T>
|
||||
* @return
|
||||
*/
|
||||
<T> boolean deleteIndex(Class<T> clazz);
|
||||
|
||||
/**
|
||||
* return number of elements found by for given query
|
||||
*
|
||||
* @param query
|
||||
* @param clazz
|
||||
* @return
|
||||
*/
|
||||
<T> long count(SearchQuery query, Class<T> clazz);
|
||||
/**
|
||||
* check if index is exists
|
||||
*
|
||||
* @param clazz
|
||||
* @param <T>
|
||||
* @return
|
||||
*/
|
||||
<T> boolean indexExists(Class<T> clazz);
|
||||
|
||||
/**
|
||||
* Index an object. Will do save or update
|
||||
*
|
||||
* @param query
|
||||
* @return returns the document id
|
||||
*/
|
||||
String index(IndexQuery query);
|
||||
/**
|
||||
* refresh the index
|
||||
*
|
||||
* @param indexName
|
||||
* @param waitForOperation
|
||||
*/
|
||||
void refresh(String indexName, boolean waitForOperation);
|
||||
|
||||
/**
|
||||
* Bulk index all objects. Will do save or update
|
||||
*
|
||||
* @param queries
|
||||
*/
|
||||
void bulkIndex(List<IndexQuery> queries);
|
||||
/**
|
||||
* refresh the index
|
||||
*
|
||||
* @param clazz
|
||||
* @param waitForOperation
|
||||
*/
|
||||
<T> void refresh(Class<T> clazz, boolean waitForOperation);
|
||||
|
||||
/**
|
||||
* Delete the one object with provided id
|
||||
*
|
||||
* @param indexName
|
||||
* @param type
|
||||
* @param id
|
||||
* @return documentId of the document deleted
|
||||
*/
|
||||
String delete(String indexName, String type, String id);
|
||||
/**
|
||||
* Returns scroll id for scan query
|
||||
*
|
||||
* @param query
|
||||
* @param scrollTimeInMillis
|
||||
* @param noFields
|
||||
* @return
|
||||
*/
|
||||
String scan(SearchQuery query, long scrollTimeInMillis, boolean noFields);
|
||||
|
||||
/**
|
||||
* Delete the one object with provided id
|
||||
*
|
||||
* @param clazz
|
||||
* @param id
|
||||
* @return documentId of the document deleted
|
||||
*/
|
||||
<T> String delete(Class<T> clazz, String id);
|
||||
/**
|
||||
* Scrolls the results for give scroll id
|
||||
*
|
||||
* @param scrollId
|
||||
* @param scrollTimeInMillis
|
||||
* @param resultsMapper
|
||||
* @param <T>
|
||||
* @return
|
||||
*/
|
||||
<T> Page<T> scroll(String scrollId, long scrollTimeInMillis, ResultsMapper<T> resultsMapper);
|
||||
|
||||
/**
|
||||
* Delete all records matching the query
|
||||
* @param clazz
|
||||
* @param query
|
||||
*/
|
||||
<T> void delete(DeleteQuery query, Class<T> clazz);
|
||||
|
||||
/**
|
||||
* Deletes an index for given entity
|
||||
* @param clazz
|
||||
* @param <T>
|
||||
* @return
|
||||
*/
|
||||
<T> boolean deleteIndex(Class<T> clazz);
|
||||
|
||||
/**
|
||||
* check if index is exists
|
||||
* @param clazz
|
||||
* @param <T>
|
||||
* @return
|
||||
*/
|
||||
<T> boolean indexExists(Class<T> clazz);
|
||||
|
||||
/**
|
||||
* refresh the index
|
||||
* @param indexName
|
||||
* @param waitForOperation
|
||||
*/
|
||||
void refresh(String indexName,boolean waitForOperation);
|
||||
|
||||
/**
|
||||
* refresh the index
|
||||
* @param clazz
|
||||
* @param waitForOperation
|
||||
*/
|
||||
<T> void refresh(Class<T> clazz,boolean waitForOperation);
|
||||
|
||||
/**
|
||||
* Returns scroll id for scan query
|
||||
* @param query
|
||||
* @param scrollTimeInMillis
|
||||
* @param noFields
|
||||
* @return
|
||||
*/
|
||||
String scan(SearchQuery query, long scrollTimeInMillis, boolean noFields);
|
||||
|
||||
/**
|
||||
* Scrolls the results for give scroll id
|
||||
* @param scrollId
|
||||
* @param scrollTimeInMillis
|
||||
* @param resultsMapper
|
||||
* @param <T>
|
||||
* @return
|
||||
*/
|
||||
<T> Page<T> scroll(String scrollId, long scrollTimeInMillis, ResultsMapper<T> resultsMapper);
|
||||
|
||||
/**
|
||||
* more like this query to search for documents that are "like" a specific document.
|
||||
* @param query
|
||||
* @param clazz
|
||||
* @param <T>
|
||||
* @return
|
||||
*/
|
||||
<T> Page<T> moreLikeThis(MoreLikeThisQuery query, Class<T> clazz);
|
||||
/**
|
||||
* more like this query to search for documents that are "like" a specific document.
|
||||
*
|
||||
* @param query
|
||||
* @param clazz
|
||||
* @param <T>
|
||||
* @return
|
||||
*/
|
||||
<T> Page<T> moreLikeThis(MoreLikeThisQuery query, Class<T> clazz);
|
||||
|
||||
}
|
||||
|
||||
@@ -69,457 +69,443 @@ import static org.springframework.data.elasticsearch.core.MappingBuilder.buildMa
|
||||
|
||||
/**
|
||||
* ElasticsearchTemplate
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
|
||||
public class ElasticsearchTemplate implements ElasticsearchOperations {
|
||||
|
||||
private Client client;
|
||||
private ElasticsearchConverter elasticsearchConverter;
|
||||
private ObjectMapper objectMapper = new ObjectMapper();
|
||||
private Client client;
|
||||
private ElasticsearchConverter elasticsearchConverter;
|
||||
private ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
{
|
||||
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
}
|
||||
{
|
||||
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
}
|
||||
|
||||
public ElasticsearchTemplate(Client client) {
|
||||
this(client, null);
|
||||
}
|
||||
public ElasticsearchTemplate(Client client) {
|
||||
this(client, null);
|
||||
}
|
||||
|
||||
public ElasticsearchTemplate(Client client, ElasticsearchConverter elasticsearchConverter) {
|
||||
this.client = client;
|
||||
this.elasticsearchConverter = (elasticsearchConverter == null)? new MappingElasticsearchConverter(new SimpleElasticsearchMappingContext()) : elasticsearchConverter ;
|
||||
}
|
||||
public ElasticsearchTemplate(Client client, ElasticsearchConverter elasticsearchConverter) {
|
||||
this.client = client;
|
||||
this.elasticsearchConverter = (elasticsearchConverter == null) ? new MappingElasticsearchConverter(
|
||||
new SimpleElasticsearchMappingContext()) : elasticsearchConverter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> boolean createIndex(Class<T> clazz) {
|
||||
ElasticsearchPersistentEntity<T> persistentEntity = getPersistentEntityFor(clazz);
|
||||
return createIndexIfNotCreated(clazz);
|
||||
}
|
||||
@Override
|
||||
public <T> boolean createIndex(Class<T> clazz) {
|
||||
ElasticsearchPersistentEntity<T> persistentEntity = getPersistentEntityFor(clazz);
|
||||
return createIndexIfNotCreated(clazz);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> boolean putMapping(Class<T> clazz) {
|
||||
ElasticsearchPersistentEntity<T> persistentEntity = getPersistentEntityFor(clazz);
|
||||
PutMappingRequestBuilder requestBuilder = client.admin().indices().preparePutMapping(persistentEntity.getIndexName())
|
||||
.setType(persistentEntity.getIndexType());
|
||||
@Override
|
||||
public <T> boolean putMapping(Class<T> clazz) {
|
||||
ElasticsearchPersistentEntity<T> persistentEntity = getPersistentEntityFor(clazz);
|
||||
PutMappingRequestBuilder requestBuilder = client.admin().indices()
|
||||
.preparePutMapping(persistentEntity.getIndexName()).setType(persistentEntity.getIndexType());
|
||||
|
||||
try {
|
||||
XContentBuilder xContentBuilder = buildMapping(clazz, persistentEntity.getIndexType(), persistentEntity.getIdProperty().getFieldName());
|
||||
return requestBuilder.setSource(xContentBuilder).execute().actionGet().isAcknowledged();
|
||||
} catch (Exception e) {
|
||||
throw new ElasticsearchException("Failed to build mapping for " + clazz.getSimpleName() , e);
|
||||
}
|
||||
}
|
||||
try {
|
||||
XContentBuilder xContentBuilder = buildMapping(clazz, persistentEntity.getIndexType(), persistentEntity
|
||||
.getIdProperty().getFieldName());
|
||||
return requestBuilder.setSource(xContentBuilder).execute().actionGet().isAcknowledged();
|
||||
} catch (Exception e) {
|
||||
throw new ElasticsearchException("Failed to build mapping for " + clazz.getSimpleName(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ElasticsearchConverter getElasticsearchConverter() {
|
||||
return elasticsearchConverter;
|
||||
}
|
||||
@Override
|
||||
public ElasticsearchConverter getElasticsearchConverter() {
|
||||
return elasticsearchConverter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T queryForObject(GetQuery query, Class<T> clazz) {
|
||||
ElasticsearchPersistentEntity<T> persistentEntity = getPersistentEntityFor(clazz);
|
||||
GetResponse response = client.prepareGet(persistentEntity.getIndexName(), persistentEntity.getIndexType(), query.getId())
|
||||
.execute().actionGet();
|
||||
return mapResult(response.getSourceAsString(), clazz);
|
||||
}
|
||||
@Override
|
||||
public <T> T queryForObject(GetQuery query, Class<T> clazz) {
|
||||
ElasticsearchPersistentEntity<T> persistentEntity = getPersistentEntityFor(clazz);
|
||||
GetResponse response = client
|
||||
.prepareGet(persistentEntity.getIndexName(), persistentEntity.getIndexType(), query.getId()).execute()
|
||||
.actionGet();
|
||||
return mapResult(response.getSourceAsString(), clazz);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T queryForObject(CriteriaQuery query, Class<T> clazz) {
|
||||
Page<T> page = queryForPage(query,clazz);
|
||||
Assert.isTrue(page.getTotalElements() < 2, "Expected 1 but found "+ page.getTotalElements() +" results");
|
||||
return page.getTotalElements() > 0? page.getContent().get(0) : null;
|
||||
}
|
||||
@Override
|
||||
public <T> T queryForObject(CriteriaQuery query, Class<T> clazz) {
|
||||
Page<T> page = queryForPage(query, clazz);
|
||||
Assert.isTrue(page.getTotalElements() < 2, "Expected 1 but found " + page.getTotalElements() + " results");
|
||||
return page.getTotalElements() > 0 ? page.getContent().get(0) : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T queryForObject(StringQuery query, Class<T> clazz) {
|
||||
Page<T> page = queryForPage(query,clazz);
|
||||
Assert.isTrue(page.getTotalElements() < 2, "Expected 1 but found "+ page.getTotalElements() +" results");
|
||||
return page.getTotalElements() > 0? page.getContent().get(0) : null;
|
||||
}
|
||||
@Override
|
||||
public <T> T queryForObject(StringQuery query, Class<T> clazz) {
|
||||
Page<T> page = queryForPage(query, clazz);
|
||||
Assert.isTrue(page.getTotalElements() < 2, "Expected 1 but found " + page.getTotalElements() + " results");
|
||||
return page.getTotalElements() > 0 ? page.getContent().get(0) : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> Page<T> queryForPage(SearchQuery query, Class<T> clazz) {
|
||||
SearchResponse response = doSearch(prepareSearch(query,clazz), query.getQuery(), query.getFilter(), query.getElasticsearchSort());
|
||||
return mapResults(response, clazz, query.getPageable());
|
||||
}
|
||||
@Override
|
||||
public <T> Page<T> queryForPage(SearchQuery query, Class<T> clazz) {
|
||||
SearchResponse response = doSearch(prepareSearch(query, clazz), query.getQuery(), query.getFilter(),
|
||||
query.getElasticsearchSort());
|
||||
return mapResults(response, clazz, query.getPageable());
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> Page<T> queryForPage(SearchQuery query, ResultsMapper<T> resultsMapper) {
|
||||
SearchResponse response = doSearch(prepareSearch(query), query.getQuery(), query.getFilter(), query.getElasticsearchSort());
|
||||
return resultsMapper.mapResults(response);
|
||||
}
|
||||
@Override
|
||||
public <T> Page<T> queryForPage(SearchQuery query, ResultsMapper<T> resultsMapper) {
|
||||
SearchResponse response = doSearch(prepareSearch(query), query.getQuery(), query.getFilter(),
|
||||
query.getElasticsearchSort());
|
||||
return resultsMapper.mapResults(response);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> List<T> queryForList(CriteriaQuery query, Class<T> clazz){
|
||||
return queryForPage(query, clazz).getContent();
|
||||
}
|
||||
@Override
|
||||
public <T> List<T> queryForList(CriteriaQuery query, Class<T> clazz) {
|
||||
return queryForPage(query, clazz).getContent();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> List<T> queryForList(StringQuery query, Class<T> clazz){
|
||||
return queryForPage(query, clazz).getContent();
|
||||
}
|
||||
@Override
|
||||
public <T> List<T> queryForList(StringQuery query, Class<T> clazz) {
|
||||
return queryForPage(query, clazz).getContent();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> List<String> queryForIds(SearchQuery query) {
|
||||
SearchRequestBuilder request = prepareSearch(query).setQuery(query.getQuery()).setNoFields();
|
||||
if (query.getFilter() != null) {
|
||||
request.setFilter(query.getFilter());
|
||||
}
|
||||
SearchResponse response = request.execute().actionGet();
|
||||
return extractIds(response);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> List<String> queryForIds(SearchQuery query) {
|
||||
SearchRequestBuilder request = prepareSearch(query).setQuery(query.getQuery())
|
||||
.setNoFields();
|
||||
if(query.getFilter() != null){
|
||||
request.setFilter(query.getFilter());
|
||||
}
|
||||
SearchResponse response = request.execute().actionGet();
|
||||
return extractIds(response);
|
||||
}
|
||||
@Override
|
||||
public <T> Page<T> queryForPage(CriteriaQuery criteriaQuery, Class<T> clazz) {
|
||||
QueryBuilder query = new CriteriaQueryProcessor().createQueryFromCriteria(criteriaQuery.getCriteria());
|
||||
SearchResponse response = prepareSearch(criteriaQuery, clazz).setQuery(query).execute().actionGet();
|
||||
return mapResults(response, clazz, criteriaQuery.getPageable());
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> Page<T> queryForPage(CriteriaQuery criteriaQuery, Class<T> clazz) {
|
||||
QueryBuilder query = new CriteriaQueryProcessor().createQueryFromCriteria(criteriaQuery.getCriteria());
|
||||
SearchResponse response = prepareSearch(criteriaQuery,clazz)
|
||||
.setQuery(query)
|
||||
.execute().actionGet();
|
||||
return mapResults(response, clazz, criteriaQuery.getPageable());
|
||||
}
|
||||
@Override
|
||||
public <T> Page<T> queryForPage(StringQuery query, Class<T> clazz) {
|
||||
SearchResponse response = prepareSearch(query, clazz).setQuery(query.getSource()).execute().actionGet();
|
||||
return mapResults(response, clazz, query.getPageable());
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> Page<T> queryForPage(StringQuery query, Class<T> clazz) {
|
||||
SearchResponse response = prepareSearch(query,clazz)
|
||||
.setQuery(query.getSource())
|
||||
.execute().actionGet();
|
||||
return mapResults(response, clazz, query.getPageable());
|
||||
}
|
||||
@Override
|
||||
public <T> long count(SearchQuery query, Class<T> clazz) {
|
||||
ElasticsearchPersistentEntity<T> persistentEntity = getPersistentEntityFor(clazz);
|
||||
CountRequestBuilder countRequestBuilder = client.prepareCount(persistentEntity.getIndexName()).setTypes(
|
||||
persistentEntity.getIndexType());
|
||||
if (query.getQuery() != null) {
|
||||
countRequestBuilder.setQuery(query.getQuery());
|
||||
}
|
||||
return countRequestBuilder.execute().actionGet().getCount();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> long count(SearchQuery query, Class<T> clazz) {
|
||||
ElasticsearchPersistentEntity<T> persistentEntity = getPersistentEntityFor(clazz);
|
||||
CountRequestBuilder countRequestBuilder = client.prepareCount(persistentEntity.getIndexName())
|
||||
.setTypes(persistentEntity.getIndexType());
|
||||
if(query.getQuery() != null){
|
||||
countRequestBuilder.setQuery(query.getQuery());
|
||||
}
|
||||
return countRequestBuilder.execute().actionGet().getCount();
|
||||
}
|
||||
@Override
|
||||
public String index(IndexQuery query) {
|
||||
return prepareIndex(query).execute().actionGet().getId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String index(IndexQuery query) {
|
||||
return prepareIndex(query)
|
||||
.execute()
|
||||
.actionGet().getId();
|
||||
}
|
||||
@Override
|
||||
public void bulkIndex(List<IndexQuery> queries) {
|
||||
BulkRequestBuilder bulkRequest = client.prepareBulk();
|
||||
for (IndexQuery query : queries) {
|
||||
bulkRequest.add(prepareIndex(query));
|
||||
}
|
||||
BulkResponse bulkResponse = bulkRequest.execute().actionGet();
|
||||
if (bulkResponse.hasFailures()) {
|
||||
Map<String, String> failedDocuments = new HashMap<String, String>();
|
||||
for (BulkItemResponse item : bulkResponse.getItems()) {
|
||||
if (item.isFailed())
|
||||
failedDocuments.put(item.getId(), item.getFailureMessage());
|
||||
}
|
||||
throw new ElasticsearchException(
|
||||
"Bulk indexing has failures. Use ElasticsearchException.getFailedDocuments() for detailed messages ["
|
||||
+ failedDocuments + "]", failedDocuments);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void bulkIndex(List<IndexQuery> queries) {
|
||||
BulkRequestBuilder bulkRequest = client.prepareBulk();
|
||||
for(IndexQuery query : queries){
|
||||
bulkRequest.add(prepareIndex(query));
|
||||
}
|
||||
BulkResponse bulkResponse = bulkRequest.execute().actionGet();
|
||||
if (bulkResponse.hasFailures()) {
|
||||
Map<String, String> failedDocuments = new HashMap<String, String>();
|
||||
for (BulkItemResponse item : bulkResponse.getItems()) {
|
||||
if (item.isFailed())
|
||||
failedDocuments.put(item.getId(), item.getFailureMessage());
|
||||
}
|
||||
throw new ElasticsearchException("Bulk indexing has failures. Use ElasticsearchException.getFailedDocuments() for detailed messages [" + failedDocuments+"]", failedDocuments);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public <T> boolean indexExists(Class<T> clazz) {
|
||||
return indexExists(getPersistentEntityFor(clazz).getIndexName());
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> boolean indexExists(Class<T> clazz){
|
||||
return indexExists(getPersistentEntityFor(clazz).getIndexName());
|
||||
}
|
||||
@Override
|
||||
public <T> boolean deleteIndex(Class<T> clazz) {
|
||||
String indexName = getPersistentEntityFor(clazz).getIndexName();
|
||||
if (indexExists(indexName)) {
|
||||
return client.admin().indices().delete(new DeleteIndexRequest(indexName)).actionGet().isAcknowledged();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> boolean deleteIndex(Class<T> clazz){
|
||||
String indexName = getPersistentEntityFor(clazz).getIndexName();
|
||||
if(indexExists(indexName)){
|
||||
return client.admin().indices().delete(new DeleteIndexRequest(indexName)).actionGet().isAcknowledged();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@Override
|
||||
public String delete(String indexName, String type, String id) {
|
||||
return client.prepareDelete(indexName, type, id).execute().actionGet().getId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String delete(String indexName, String type, String id) {
|
||||
return client.prepareDelete(indexName, type, id)
|
||||
.execute().actionGet().getId();
|
||||
}
|
||||
@Override
|
||||
public <T> String delete(Class<T> clazz, String id) {
|
||||
ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz);
|
||||
return delete(persistentEntity.getIndexName(), persistentEntity.getIndexType(), id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> String delete(Class<T> clazz, String id) {
|
||||
ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz);
|
||||
return delete(persistentEntity.getIndexName(), persistentEntity.getIndexType(), id);
|
||||
}
|
||||
@Override
|
||||
public <T> void delete(DeleteQuery deleteQuery, Class<T> clazz) {
|
||||
ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz);
|
||||
client.prepareDeleteByQuery(persistentEntity.getIndexName()).setTypes(persistentEntity.getIndexType())
|
||||
.setQuery(deleteQuery.getQuery()).execute().actionGet();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> void delete(DeleteQuery deleteQuery, Class<T> clazz) {
|
||||
ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz);
|
||||
client.prepareDeleteByQuery(persistentEntity.getIndexName())
|
||||
.setTypes(persistentEntity.getIndexType())
|
||||
.setQuery(deleteQuery.getQuery())
|
||||
.execute().actionGet();
|
||||
}
|
||||
@Override
|
||||
public String scan(SearchQuery searchQuery, long scrollTimeInMillis, boolean noFields) {
|
||||
Assert.notNull(searchQuery.getIndices(), "No index defined for Query");
|
||||
Assert.notNull(searchQuery.getTypes(), "No type define for Query");
|
||||
Assert.notNull(searchQuery.getPageable(), "Query.pageable is required for scan & scroll");
|
||||
|
||||
@Override
|
||||
public String scan(SearchQuery searchQuery, long scrollTimeInMillis, boolean noFields) {
|
||||
Assert.notNull(searchQuery.getIndices(), "No index defined for Query");
|
||||
Assert.notNull(searchQuery.getTypes(), "No type define for Query");
|
||||
Assert.notNull(searchQuery.getPageable(), "Query.pageable is required for scan & scroll");
|
||||
SearchRequestBuilder requestBuilder = client.prepareSearch(toArray(searchQuery.getIndices())).setSearchType(SCAN)
|
||||
.setQuery(searchQuery.getQuery()).setTypes(toArray(searchQuery.getTypes()))
|
||||
.setScroll(TimeValue.timeValueMillis(scrollTimeInMillis)).setFrom(0)
|
||||
.setSize(searchQuery.getPageable().getPageSize());
|
||||
|
||||
SearchRequestBuilder requestBuilder = client.prepareSearch(toArray(searchQuery.getIndices()))
|
||||
.setSearchType(SCAN)
|
||||
.setQuery(searchQuery.getQuery())
|
||||
.setTypes(toArray(searchQuery.getTypes()))
|
||||
.setScroll(TimeValue.timeValueMillis(scrollTimeInMillis))
|
||||
.setFrom(0)
|
||||
.setSize(searchQuery.getPageable().getPageSize());
|
||||
if (searchQuery.getFilter() != null) {
|
||||
requestBuilder.setFilter(searchQuery.getFilter());
|
||||
}
|
||||
|
||||
if(searchQuery.getFilter() != null){
|
||||
requestBuilder.setFilter(searchQuery.getFilter());
|
||||
}
|
||||
if (noFields) {
|
||||
requestBuilder.setNoFields();
|
||||
}
|
||||
return requestBuilder.execute().actionGet().getScrollId();
|
||||
}
|
||||
|
||||
if(noFields){
|
||||
requestBuilder.setNoFields();
|
||||
}
|
||||
return requestBuilder.execute().actionGet().getScrollId();
|
||||
}
|
||||
@Override
|
||||
public <T> Page<T> scroll(String scrollId, long scrollTimeInMillis, ResultsMapper<T> resultsMapper) {
|
||||
SearchResponse response = client.prepareSearchScroll(scrollId)
|
||||
.setScroll(TimeValue.timeValueMillis(scrollTimeInMillis)).execute().actionGet();
|
||||
return resultsMapper.mapResults(response);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> Page<T> scroll(String scrollId, long scrollTimeInMillis, ResultsMapper<T> resultsMapper) {
|
||||
SearchResponse response = client.prepareSearchScroll(scrollId)
|
||||
.setScroll(TimeValue.timeValueMillis(scrollTimeInMillis))
|
||||
.execute().actionGet();
|
||||
return resultsMapper.mapResults(response);
|
||||
}
|
||||
@Override
|
||||
public <T> Page<T> moreLikeThis(MoreLikeThisQuery query, Class<T> clazz) {
|
||||
int startRecord = 0;
|
||||
ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz);
|
||||
String indexName = isNotBlank(query.getIndexName()) ? query.getIndexName() : persistentEntity.getIndexName();
|
||||
String type = isNotBlank(query.getType()) ? query.getType() : persistentEntity.getIndexType();
|
||||
|
||||
@Override
|
||||
public <T> Page<T> moreLikeThis(MoreLikeThisQuery query, Class<T> clazz) {
|
||||
int startRecord = 0;
|
||||
ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz);
|
||||
String indexName = isNotBlank(query.getIndexName())? query.getIndexName(): persistentEntity.getIndexName();
|
||||
String type = isNotBlank(query.getType())? query.getType() : persistentEntity.getIndexType();
|
||||
Assert.notNull(indexName, "No 'indexName' defined for MoreLikeThisQuery");
|
||||
Assert.notNull(type, "No 'type' defined for MoreLikeThisQuery");
|
||||
Assert.notNull(query.getId(), "No document id defined for MoreLikeThisQuery");
|
||||
|
||||
Assert.notNull(indexName,"No 'indexName' defined for MoreLikeThisQuery");
|
||||
Assert.notNull(type, "No 'type' defined for MoreLikeThisQuery");
|
||||
Assert.notNull(query.getId(), "No document id defined for MoreLikeThisQuery");
|
||||
MoreLikeThisRequestBuilder requestBuilder = client.prepareMoreLikeThis(indexName, type, query.getId());
|
||||
|
||||
MoreLikeThisRequestBuilder requestBuilder =
|
||||
client.prepareMoreLikeThis(indexName,type, query.getId());
|
||||
if (query.getPageable() != null) {
|
||||
startRecord = query.getPageable().getPageNumber() * query.getPageable().getPageSize();
|
||||
requestBuilder.setSearchSize(query.getPageable().getPageSize());
|
||||
}
|
||||
requestBuilder.setSearchFrom(startRecord);
|
||||
|
||||
if(query.getPageable() != null){
|
||||
startRecord = query.getPageable().getPageNumber() * query.getPageable().getPageSize();
|
||||
requestBuilder.setSearchSize(query.getPageable().getPageSize());
|
||||
}
|
||||
requestBuilder.setSearchFrom(startRecord);
|
||||
if (isNotEmpty(query.getSearchIndices())) {
|
||||
requestBuilder.setSearchIndices(toArray(query.getSearchIndices()));
|
||||
}
|
||||
if (isNotEmpty(query.getSearchTypes())) {
|
||||
requestBuilder.setSearchTypes(toArray(query.getSearchTypes()));
|
||||
}
|
||||
if (isNotEmpty(query.getFields())) {
|
||||
requestBuilder.setField(toArray(query.getFields()));
|
||||
}
|
||||
if (isNotBlank(query.getRouting())) {
|
||||
requestBuilder.setRouting(query.getRouting());
|
||||
}
|
||||
if (query.getPercentTermsToMatch() != null) {
|
||||
requestBuilder.setPercentTermsToMatch(query.getPercentTermsToMatch());
|
||||
}
|
||||
if (query.getMinTermFreq() != null) {
|
||||
requestBuilder.setMinTermFreq(query.getMinTermFreq());
|
||||
}
|
||||
if (query.getMaxQueryTerms() != null) {
|
||||
requestBuilder.maxQueryTerms(query.getMaxQueryTerms());
|
||||
}
|
||||
if (isNotEmpty(query.getStopWords())) {
|
||||
requestBuilder.setStopWords(toArray(query.getStopWords()));
|
||||
}
|
||||
if (query.getMinDocFreq() != null) {
|
||||
requestBuilder.setMinDocFreq(query.getMinDocFreq());
|
||||
}
|
||||
if (query.getMaxDocFreq() != null) {
|
||||
requestBuilder.setMaxDocFreq(query.getMaxDocFreq());
|
||||
}
|
||||
if (query.getMinWordLen() != null) {
|
||||
requestBuilder.setMinWordLen(query.getMinWordLen());
|
||||
}
|
||||
if (query.getMaxWordLen() != null) {
|
||||
requestBuilder.setMaxWordLen(query.getMaxWordLen());
|
||||
}
|
||||
if (query.getBoostTerms() != null) {
|
||||
requestBuilder.setBoostTerms(query.getBoostTerms());
|
||||
}
|
||||
|
||||
if(isNotEmpty(query.getSearchIndices())){
|
||||
requestBuilder.setSearchIndices(toArray(query.getSearchIndices()));
|
||||
}
|
||||
if(isNotEmpty(query.getSearchTypes())){
|
||||
requestBuilder.setSearchTypes(toArray(query.getSearchTypes()));
|
||||
}
|
||||
if(isNotEmpty(query.getFields())){
|
||||
requestBuilder.setField(toArray(query.getFields()));
|
||||
}
|
||||
if(isNotBlank(query.getRouting())){
|
||||
requestBuilder.setRouting(query.getRouting());
|
||||
}
|
||||
if(query.getPercentTermsToMatch() != null){
|
||||
requestBuilder.setPercentTermsToMatch(query.getPercentTermsToMatch());
|
||||
}
|
||||
if(query.getMinTermFreq() != null){
|
||||
requestBuilder.setMinTermFreq(query.getMinTermFreq());
|
||||
}
|
||||
if(query.getMaxQueryTerms() != null){
|
||||
requestBuilder.maxQueryTerms(query.getMaxQueryTerms());
|
||||
}
|
||||
if(isNotEmpty(query.getStopWords())){
|
||||
requestBuilder.setStopWords(toArray(query.getStopWords()));
|
||||
}
|
||||
if(query.getMinDocFreq() != null){
|
||||
requestBuilder.setMinDocFreq(query.getMinDocFreq());
|
||||
}
|
||||
if(query.getMaxDocFreq() != null){
|
||||
requestBuilder.setMaxDocFreq(query.getMaxDocFreq());
|
||||
}
|
||||
if(query.getMinWordLen() != null){
|
||||
requestBuilder.setMinWordLen(query.getMinWordLen());
|
||||
}
|
||||
if(query.getMaxWordLen() != null){
|
||||
requestBuilder.setMaxWordLen(query.getMaxWordLen());
|
||||
}
|
||||
if(query.getBoostTerms() != null){
|
||||
requestBuilder.setBoostTerms(query.getBoostTerms());
|
||||
}
|
||||
SearchResponse response = requestBuilder.execute().actionGet();
|
||||
return mapResults(response, clazz, query.getPageable());
|
||||
}
|
||||
|
||||
SearchResponse response = requestBuilder.execute().actionGet();
|
||||
return mapResults(response, clazz, query.getPageable());
|
||||
}
|
||||
private SearchResponse doSearch(SearchRequestBuilder searchRequest, QueryBuilder query, FilterBuilder filter,
|
||||
SortBuilder sortBuilder) {
|
||||
if (filter != null) {
|
||||
searchRequest.setFilter(filter);
|
||||
}
|
||||
|
||||
private SearchResponse doSearch(SearchRequestBuilder searchRequest, QueryBuilder query, FilterBuilder filter, SortBuilder sortBuilder){
|
||||
if(filter != null){
|
||||
searchRequest.setFilter(filter);
|
||||
}
|
||||
if (sortBuilder != null) {
|
||||
searchRequest.addSort(sortBuilder);
|
||||
}
|
||||
|
||||
if(sortBuilder != null){
|
||||
searchRequest.addSort(sortBuilder);
|
||||
}
|
||||
return searchRequest.setQuery(query).execute().actionGet();
|
||||
}
|
||||
|
||||
return searchRequest.setQuery(query).execute().actionGet();
|
||||
}
|
||||
private <T> boolean createIndexIfNotCreated(Class<T> clazz) {
|
||||
return indexExists(getPersistentEntityFor(clazz).getIndexName()) || createIndexWithSettings(clazz);
|
||||
}
|
||||
|
||||
private <T> boolean createIndexIfNotCreated(Class<T> clazz) {
|
||||
return indexExists(getPersistentEntityFor(clazz).getIndexName()) || createIndexWithSettings(clazz);
|
||||
}
|
||||
private boolean indexExists(String indexName) {
|
||||
return client.admin().indices().exists(indicesExistsRequest(indexName)).actionGet().isExists();
|
||||
}
|
||||
|
||||
private boolean indexExists(String indexName) {
|
||||
return client.admin()
|
||||
.indices()
|
||||
.exists(indicesExistsRequest(indexName)).actionGet().isExists();
|
||||
}
|
||||
private <T> boolean createIndexWithSettings(Class<T> clazz) {
|
||||
ElasticsearchPersistentEntity<T> persistentEntity = getPersistentEntityFor(clazz);
|
||||
return client.admin().indices()
|
||||
.create(Requests.createIndexRequest(persistentEntity.getIndexName()).settings(getSettings(persistentEntity)))
|
||||
.actionGet().isAcknowledged();
|
||||
}
|
||||
|
||||
private <T> boolean createIndexWithSettings(Class<T> clazz) {
|
||||
ElasticsearchPersistentEntity<T> persistentEntity = getPersistentEntityFor(clazz);
|
||||
return client.admin().indices().create(Requests.createIndexRequest(persistentEntity.getIndexName()).
|
||||
settings(getSettings(persistentEntity))).actionGet().isAcknowledged();
|
||||
}
|
||||
private <T> Map getSettings(ElasticsearchPersistentEntity<T> persistentEntity) {
|
||||
return new MapBuilder<String, String>().put("index.number_of_shards", String.valueOf(persistentEntity.getShards()))
|
||||
.put("index.number_of_replicas", String.valueOf(persistentEntity.getReplicas()))
|
||||
.put("index.refresh_interval", persistentEntity.getRefreshInterval())
|
||||
.put("index.store.type", persistentEntity.getIndexStoreType()).map();
|
||||
}
|
||||
|
||||
private <T> Map getSettings(ElasticsearchPersistentEntity<T> persistentEntity) {
|
||||
return new MapBuilder<String, String>()
|
||||
.put("index.number_of_shards", String.valueOf(persistentEntity.getShards()))
|
||||
.put("index.number_of_replicas", String.valueOf(persistentEntity.getReplicas()))
|
||||
.put("index.refresh_interval", persistentEntity.getRefreshInterval())
|
||||
.put("index.store.type", persistentEntity.getIndexStoreType())
|
||||
.map();
|
||||
}
|
||||
private <T> SearchRequestBuilder prepareSearch(Query query, Class<T> clazz) {
|
||||
if (query.getIndices().isEmpty()) {
|
||||
query.addIndices(retrieveIndexNameFromPersistentEntity(clazz));
|
||||
}
|
||||
if (query.getTypes().isEmpty()) {
|
||||
query.addTypes(retrieveTypeFromPersistentEntity(clazz));
|
||||
}
|
||||
return prepareSearch(query);
|
||||
}
|
||||
|
||||
private <T> SearchRequestBuilder prepareSearch(Query query, Class<T> clazz){
|
||||
if(query.getIndices().isEmpty()){
|
||||
query.addIndices(retrieveIndexNameFromPersistentEntity(clazz));
|
||||
}
|
||||
if(query.getTypes().isEmpty()){
|
||||
query.addTypes(retrieveTypeFromPersistentEntity(clazz));
|
||||
}
|
||||
return prepareSearch(query);
|
||||
}
|
||||
private SearchRequestBuilder prepareSearch(Query query) {
|
||||
Assert.notNull(query.getIndices(), "No index defined for Query");
|
||||
Assert.notNull(query.getTypes(), "No type defined for Query");
|
||||
|
||||
private SearchRequestBuilder prepareSearch(Query query){
|
||||
Assert.notNull(query.getIndices(), "No index defined for Query");
|
||||
Assert.notNull(query.getTypes(), "No type defined for Query");
|
||||
int startRecord = 0;
|
||||
SearchRequestBuilder searchRequestBuilder = client.prepareSearch(toArray(query.getIndices()))
|
||||
.setSearchType(DFS_QUERY_THEN_FETCH).setTypes(toArray(query.getTypes()));
|
||||
|
||||
int startRecord = 0;
|
||||
SearchRequestBuilder searchRequestBuilder = client.prepareSearch(toArray(query.getIndices()))
|
||||
.setSearchType(DFS_QUERY_THEN_FETCH)
|
||||
.setTypes(toArray(query.getTypes()));
|
||||
if (query.getPageable() != null) {
|
||||
startRecord = query.getPageable().getPageNumber() * query.getPageable().getPageSize();
|
||||
searchRequestBuilder.setSize(query.getPageable().getPageSize());
|
||||
}
|
||||
searchRequestBuilder.setFrom(startRecord);
|
||||
|
||||
if(query.getPageable() != null){
|
||||
startRecord = query.getPageable().getPageNumber() * query.getPageable().getPageSize();
|
||||
searchRequestBuilder.setSize(query.getPageable().getPageSize());
|
||||
}
|
||||
searchRequestBuilder.setFrom(startRecord);
|
||||
if (!query.getFields().isEmpty()) {
|
||||
searchRequestBuilder.addFields(toArray(query.getFields()));
|
||||
}
|
||||
|
||||
if (query.getSort() != null) {
|
||||
for (Sort.Order order : query.getSort()) {
|
||||
searchRequestBuilder.addSort(order.getProperty(), order.getDirection() == Sort.Direction.DESC ? SortOrder.DESC
|
||||
: SortOrder.ASC);
|
||||
}
|
||||
}
|
||||
return searchRequestBuilder;
|
||||
}
|
||||
|
||||
if(!query.getFields().isEmpty()){
|
||||
searchRequestBuilder.addFields(toArray(query.getFields()));
|
||||
}
|
||||
private IndexRequestBuilder prepareIndex(IndexQuery query) {
|
||||
try {
|
||||
String indexName = isBlank(query.getIndexName()) ? retrieveIndexNameFromPersistentEntity(query.getObject()
|
||||
.getClass())[0] : query.getIndexName();
|
||||
String type = isBlank(query.getType()) ? retrieveTypeFromPersistentEntity(query.getObject().getClass())[0]
|
||||
: query.getType();
|
||||
|
||||
if(query.getSort() != null){
|
||||
for(Sort.Order order : query.getSort()){
|
||||
searchRequestBuilder.addSort(order.getProperty(), order.getDirection() == Sort.Direction.DESC? SortOrder.DESC : SortOrder.ASC);
|
||||
}
|
||||
}
|
||||
return searchRequestBuilder;
|
||||
}
|
||||
IndexRequestBuilder indexRequestBuilder = client.prepareIndex(indexName, type, query.getId()).setSource(
|
||||
objectMapper.writeValueAsString(query.getObject()));
|
||||
|
||||
private IndexRequestBuilder prepareIndex(IndexQuery query){
|
||||
try {
|
||||
String indexName = isBlank(query.getIndexName())?
|
||||
retrieveIndexNameFromPersistentEntity(query.getObject().getClass())[0] : query.getIndexName();
|
||||
String type = isBlank(query.getType())?
|
||||
retrieveTypeFromPersistentEntity(query.getObject().getClass())[0] : query.getType();
|
||||
if (query.getVersion() != null) {
|
||||
indexRequestBuilder.setVersion(query.getVersion());
|
||||
indexRequestBuilder.setVersionType(EXTERNAL);
|
||||
}
|
||||
return indexRequestBuilder;
|
||||
} catch (IOException e) {
|
||||
throw new ElasticsearchException("failed to index the document [id: " + query.getId() + "]", e);
|
||||
}
|
||||
}
|
||||
|
||||
IndexRequestBuilder indexRequestBuilder = client.prepareIndex(indexName,type,query.getId())
|
||||
.setSource(objectMapper.writeValueAsString(query.getObject()));
|
||||
public void refresh(String indexName, boolean waitForOperation) {
|
||||
client.admin().indices().refresh(refreshRequest(indexName).waitForOperations(waitForOperation)).actionGet();
|
||||
}
|
||||
|
||||
if(query.getVersion() != null){
|
||||
indexRequestBuilder.setVersion(query.getVersion());
|
||||
indexRequestBuilder.setVersionType(EXTERNAL);
|
||||
}
|
||||
return indexRequestBuilder;
|
||||
} catch (IOException e) {
|
||||
throw new ElasticsearchException("failed to index the document [id: " + query.getId() +"]",e);
|
||||
}
|
||||
}
|
||||
public <T> void refresh(Class<T> clazz, boolean waitForOperation) {
|
||||
ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz);
|
||||
client.admin().indices()
|
||||
.refresh(refreshRequest(persistentEntity.getIndexName()).waitForOperations(waitForOperation)).actionGet();
|
||||
}
|
||||
|
||||
public void refresh(String indexName, boolean waitForOperation) {
|
||||
client.admin().indices()
|
||||
.refresh(refreshRequest(indexName).waitForOperations(waitForOperation)).actionGet();
|
||||
}
|
||||
private ElasticsearchPersistentEntity getPersistentEntityFor(Class clazz) {
|
||||
Assert.isTrue(clazz.isAnnotationPresent(Document.class), "Unable to identify index name. " + clazz.getSimpleName()
|
||||
+ " is not a Document. Make sure the document class is annotated with @Document(indexName=\"foo\")");
|
||||
return elasticsearchConverter.getMappingContext().getPersistentEntity(clazz);
|
||||
}
|
||||
|
||||
public <T> void refresh(Class<T> clazz, boolean waitForOperation) {
|
||||
ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz);
|
||||
client.admin().indices()
|
||||
.refresh(refreshRequest(persistentEntity.getIndexName()).waitForOperations(waitForOperation)).actionGet();
|
||||
}
|
||||
private String[] retrieveIndexNameFromPersistentEntity(Class clazz) {
|
||||
return new String[] { getPersistentEntityFor(clazz).getIndexName() };
|
||||
}
|
||||
|
||||
private ElasticsearchPersistentEntity getPersistentEntityFor(Class clazz){
|
||||
Assert.isTrue(clazz.isAnnotationPresent(Document.class), "Unable to identify index name. " +
|
||||
clazz.getSimpleName() + " is not a Document. Make sure the document class is annotated with @Document(indexName=\"foo\")");
|
||||
return elasticsearchConverter.getMappingContext().getPersistentEntity(clazz);
|
||||
}
|
||||
private String[] retrieveTypeFromPersistentEntity(Class clazz) {
|
||||
return new String[] { getPersistentEntityFor(clazz).getIndexType() };
|
||||
}
|
||||
|
||||
private String[] retrieveIndexNameFromPersistentEntity(Class clazz){
|
||||
return new String[]{getPersistentEntityFor(clazz).getIndexName()};
|
||||
}
|
||||
private <T> Page<T> mapResults(SearchResponse response, final Class<T> elementType, final Pageable pageable) {
|
||||
ResultsMapper<T> resultsMapper = new ResultsMapper<T>() {
|
||||
@Override
|
||||
public Page<T> mapResults(SearchResponse response) {
|
||||
long totalHits = response.getHits().totalHits();
|
||||
List<T> results = new ArrayList<T>();
|
||||
for (SearchHit hit : response.getHits()) {
|
||||
if (hit != null) {
|
||||
results.add(mapResult(hit.sourceAsString(), elementType));
|
||||
}
|
||||
}
|
||||
return new PageImpl<T>(results, pageable, totalHits);
|
||||
}
|
||||
};
|
||||
return resultsMapper.mapResults(response);
|
||||
}
|
||||
|
||||
private String[] retrieveTypeFromPersistentEntity(Class clazz){
|
||||
return new String[]{getPersistentEntityFor(clazz).getIndexType()};
|
||||
}
|
||||
private List<String> extractIds(SearchResponse response) {
|
||||
List<String> ids = new ArrayList<String>();
|
||||
for (SearchHit hit : response.getHits()) {
|
||||
if (hit != null) {
|
||||
ids.add(hit.getId());
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
private <T> Page<T> mapResults(SearchResponse response, final Class<T> elementType,final Pageable pageable){
|
||||
ResultsMapper<T> resultsMapper = new ResultsMapper<T>(){
|
||||
@Override
|
||||
public Page<T> mapResults(SearchResponse response) {
|
||||
long totalHits = response.getHits().totalHits();
|
||||
List<T> results = new ArrayList<T>();
|
||||
for (SearchHit hit : response.getHits()) {
|
||||
if (hit != null) {
|
||||
results.add(mapResult(hit.sourceAsString(), elementType));
|
||||
}
|
||||
}
|
||||
return new PageImpl<T>(results, pageable, totalHits);
|
||||
}
|
||||
};
|
||||
return resultsMapper.mapResults(response);
|
||||
}
|
||||
private <T> T mapResult(String source, Class<T> clazz) {
|
||||
if (isBlank(source)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(source, clazz);
|
||||
} catch (IOException e) {
|
||||
throw new ElasticsearchException("failed to map source [ " + source + "] to class " + clazz.getSimpleName(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private List<String> extractIds(SearchResponse response){
|
||||
List<String> ids = new ArrayList<String>();
|
||||
for (SearchHit hit : response.getHits()) {
|
||||
if (hit != null) {
|
||||
ids.add(hit.getId());
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
private static String[] toArray(List<String> values) {
|
||||
String[] valuesAsArray = new String[values.size()];
|
||||
return values.toArray(valuesAsArray);
|
||||
|
||||
private <T> T mapResult(String source, Class<T> clazz){
|
||||
if(isBlank(source)){
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(source, clazz);
|
||||
} catch (IOException e) {
|
||||
throw new ElasticsearchException("failed to map source [ " + source + "] to class " + clazz.getSimpleName() , e);
|
||||
}
|
||||
}
|
||||
|
||||
private static String[] toArray(List<String> values){
|
||||
String[] valuesAsArray = new String[values.size()];
|
||||
return values.toArray(valuesAsArray);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -15,7 +15,6 @@
|
||||
*/
|
||||
package org.springframework.data.elasticsearch.core;
|
||||
|
||||
|
||||
import org.elasticsearch.common.xcontent.XContentBuilder;
|
||||
import org.springframework.data.elasticsearch.annotations.Field;
|
||||
import org.springframework.data.mapping.model.SimpleTypeHolder;
|
||||
@@ -36,95 +35,86 @@ import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
|
||||
|
||||
class MappingBuilder {
|
||||
|
||||
private static SimpleTypeHolder SIMPLE_TYPE_HOLDER = new SimpleTypeHolder();
|
||||
private static SimpleTypeHolder SIMPLE_TYPE_HOLDER = new SimpleTypeHolder();
|
||||
|
||||
static XContentBuilder buildMapping(Class clazz, String indexType, String idFieldName) throws IOException {
|
||||
XContentBuilder xContentBuilder = jsonBuilder()
|
||||
.startObject().startObject(indexType).startObject("properties");
|
||||
static XContentBuilder buildMapping(Class clazz, String indexType, String idFieldName) throws IOException {
|
||||
XContentBuilder xContentBuilder = jsonBuilder().startObject().startObject(indexType).startObject("properties");
|
||||
|
||||
mapEntity(xContentBuilder, clazz, true, idFieldName, EMPTY);
|
||||
mapEntity(xContentBuilder, clazz, true, idFieldName, EMPTY);
|
||||
|
||||
return xContentBuilder.endObject().endObject().endObject();
|
||||
}
|
||||
return xContentBuilder.endObject().endObject().endObject();
|
||||
}
|
||||
|
||||
private static void mapEntity(XContentBuilder xContentBuilder,
|
||||
Class clazz,
|
||||
boolean isRootObject,
|
||||
String idFieldName,
|
||||
String nestedObjectFieldName) throws IOException{
|
||||
private static void mapEntity(XContentBuilder xContentBuilder, Class clazz, boolean isRootObject, String idFieldName,
|
||||
String nestedObjectFieldName) throws IOException {
|
||||
|
||||
java.lang.reflect.Field[] fields = clazz.getDeclaredFields();
|
||||
java.lang.reflect.Field[] fields = clazz.getDeclaredFields();
|
||||
|
||||
if(!isRootObject && isAnyPropertyAnnotatedAsField(fields)){
|
||||
xContentBuilder.startObject(nestedObjectFieldName)
|
||||
.field("type", "object")
|
||||
.startObject("properties");
|
||||
}
|
||||
if (!isRootObject && isAnyPropertyAnnotatedAsField(fields)) {
|
||||
xContentBuilder.startObject(nestedObjectFieldName).field("type", "object").startObject("properties");
|
||||
}
|
||||
|
||||
for(java.lang.reflect.Field field : fields){
|
||||
if(isEntity(field)){
|
||||
mapEntity(xContentBuilder, field.getType(), false, EMPTY, field.getName());
|
||||
}
|
||||
Field fieldAnnotation = field.getAnnotation(Field.class);
|
||||
if(isRootObject && fieldAnnotation != null && isIdField(field, idFieldName)){
|
||||
applyDefaultIdFieldMapping(xContentBuilder, field);
|
||||
}else if(fieldAnnotation != null){
|
||||
applyFieldAnnotationMapping(xContentBuilder, field, fieldAnnotation);
|
||||
}
|
||||
}
|
||||
for (java.lang.reflect.Field field : fields) {
|
||||
if (isEntity(field)) {
|
||||
mapEntity(xContentBuilder, field.getType(), false, EMPTY, field.getName());
|
||||
}
|
||||
Field fieldAnnotation = field.getAnnotation(Field.class);
|
||||
if (isRootObject && fieldAnnotation != null && isIdField(field, idFieldName)) {
|
||||
applyDefaultIdFieldMapping(xContentBuilder, field);
|
||||
} else if (fieldAnnotation != null) {
|
||||
applyFieldAnnotationMapping(xContentBuilder, field, fieldAnnotation);
|
||||
}
|
||||
}
|
||||
|
||||
if(!isRootObject && isAnyPropertyAnnotatedAsField(fields)){
|
||||
xContentBuilder.endObject().endObject();
|
||||
}
|
||||
if (!isRootObject && isAnyPropertyAnnotatedAsField(fields)) {
|
||||
xContentBuilder.endObject().endObject();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private static void applyDefaultIdFieldMapping(XContentBuilder xContentBuilder, java.lang.reflect.Field field) throws IOException {
|
||||
xContentBuilder.startObject(field.getName())
|
||||
.field("type", "string")
|
||||
.field("index", "not_analyzed")
|
||||
.endObject();
|
||||
}
|
||||
private static void applyDefaultIdFieldMapping(XContentBuilder xContentBuilder, java.lang.reflect.Field field)
|
||||
throws IOException {
|
||||
xContentBuilder.startObject(field.getName()).field("type", "string").field("index", "not_analyzed").endObject();
|
||||
}
|
||||
|
||||
private static void applyFieldAnnotationMapping(XContentBuilder xContentBuilder,
|
||||
java.lang.reflect.Field field,
|
||||
Field fieldAnnotation) throws IOException {
|
||||
xContentBuilder.startObject(field.getName());
|
||||
xContentBuilder.field("store", fieldAnnotation.store());
|
||||
if(isNotBlank(fieldAnnotation.type())){
|
||||
xContentBuilder.field("type", fieldAnnotation.type());
|
||||
}
|
||||
if(isNotBlank(fieldAnnotation.index())){
|
||||
xContentBuilder.field("index", fieldAnnotation.index());
|
||||
}
|
||||
if(isNotBlank(fieldAnnotation.searchAnalyzer())){
|
||||
xContentBuilder.field("search_analyzer", fieldAnnotation.searchAnalyzer());
|
||||
}
|
||||
if(isNotBlank(fieldAnnotation.indexAnalyzer())){
|
||||
xContentBuilder.field("index_analyzer", fieldAnnotation.indexAnalyzer());
|
||||
}
|
||||
xContentBuilder.endObject();
|
||||
}
|
||||
private static void applyFieldAnnotationMapping(XContentBuilder xContentBuilder, java.lang.reflect.Field field,
|
||||
Field fieldAnnotation) throws IOException {
|
||||
xContentBuilder.startObject(field.getName());
|
||||
xContentBuilder.field("store", fieldAnnotation.store());
|
||||
if (isNotBlank(fieldAnnotation.type())) {
|
||||
xContentBuilder.field("type", fieldAnnotation.type());
|
||||
}
|
||||
if (isNotBlank(fieldAnnotation.index())) {
|
||||
xContentBuilder.field("index", fieldAnnotation.index());
|
||||
}
|
||||
if (isNotBlank(fieldAnnotation.searchAnalyzer())) {
|
||||
xContentBuilder.field("search_analyzer", fieldAnnotation.searchAnalyzer());
|
||||
}
|
||||
if (isNotBlank(fieldAnnotation.indexAnalyzer())) {
|
||||
xContentBuilder.field("index_analyzer", fieldAnnotation.indexAnalyzer());
|
||||
}
|
||||
xContentBuilder.endObject();
|
||||
}
|
||||
|
||||
private static boolean isEntity(java.lang.reflect.Field field) {
|
||||
TypeInformation typeInformation = ClassTypeInformation.from(field.getType());
|
||||
TypeInformation<?> actualType = typeInformation.getActualType();
|
||||
boolean isComplexType = actualType == null ? false : !SIMPLE_TYPE_HOLDER.isSimpleType(actualType.getType());
|
||||
return isComplexType && !actualType.isCollectionLike() && !Map.class.isAssignableFrom(typeInformation.getType());
|
||||
}
|
||||
private static boolean isEntity(java.lang.reflect.Field field) {
|
||||
TypeInformation typeInformation = ClassTypeInformation.from(field.getType());
|
||||
TypeInformation<?> actualType = typeInformation.getActualType();
|
||||
boolean isComplexType = actualType == null ? false : !SIMPLE_TYPE_HOLDER.isSimpleType(actualType.getType());
|
||||
return isComplexType && !actualType.isCollectionLike() && !Map.class.isAssignableFrom(typeInformation.getType());
|
||||
}
|
||||
|
||||
private static boolean isAnyPropertyAnnotatedAsField(java.lang.reflect.Field[] fields){
|
||||
if(fields != null){
|
||||
for(java.lang.reflect.Field field : fields){
|
||||
if (field.isAnnotationPresent(Field.class)){
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
private static boolean isAnyPropertyAnnotatedAsField(java.lang.reflect.Field[] fields) {
|
||||
if (fields != null) {
|
||||
for (java.lang.reflect.Field field : fields) {
|
||||
if (field.isAnnotationPresent(Field.class)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean isIdField(java.lang.reflect.Field field, String idFieldName){
|
||||
return idFieldName.equals(field.getName());
|
||||
}
|
||||
private static boolean isIdField(java.lang.reflect.Field field, String idFieldName) {
|
||||
return idFieldName.equals(field.getName());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,15 +20,16 @@ import org.springframework.data.domain.Page;
|
||||
|
||||
/**
|
||||
* ResultsMapper
|
||||
*
|
||||
* @param <T>
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*
|
||||
*
|
||||
*/
|
||||
|
||||
public interface ResultsMapper<T> {
|
||||
|
||||
Page<T> mapResults(SearchResponse response);
|
||||
Page<T> mapResults(SearchResponse response);
|
||||
|
||||
}
|
||||
|
||||
@@ -25,15 +25,15 @@ import org.springframework.core.convert.converter.Converter;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* DateTimeConverters
|
||||
*
|
||||
* DateTimeConverters
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
|
||||
public final class DateTimeConverters {
|
||||
|
||||
private static DateTimeFormatter formatter = ISODateTimeFormat.dateTime().withZone(DateTimeZone.UTC);
|
||||
private static DateTimeFormatter formatter = ISODateTimeFormat.dateTime().withZone(DateTimeZone.UTC);
|
||||
|
||||
public enum JodaDateTimeConverter implements Converter<ReadableInstant, String> {
|
||||
INSTANCE;
|
||||
|
||||
@@ -21,26 +21,26 @@ import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersiste
|
||||
import org.springframework.data.mapping.context.MappingContext;
|
||||
|
||||
/**
|
||||
* ElasticsearchConverter
|
||||
*
|
||||
* ElasticsearchConverter
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
|
||||
public interface ElasticsearchConverter{
|
||||
public interface ElasticsearchConverter {
|
||||
|
||||
/**
|
||||
* Returns the underlying {@link org.springframework.data.mapping.context.MappingContext} used by the converter.
|
||||
*
|
||||
* @return never {@literal null}
|
||||
*/
|
||||
MappingContext<? extends ElasticsearchPersistentEntity<?>, ElasticsearchPersistentProperty> getMappingContext();
|
||||
/**
|
||||
* Returns the underlying {@link org.springframework.data.mapping.context.MappingContext} used by the converter.
|
||||
*
|
||||
* @return never {@literal null}
|
||||
*/
|
||||
MappingContext<? extends ElasticsearchPersistentEntity<?>, ElasticsearchPersistentProperty> getMappingContext();
|
||||
|
||||
/**
|
||||
* Returns the underlying {@link org.springframework.core.convert.ConversionService} used by the converter.
|
||||
*
|
||||
* @return never {@literal null}.
|
||||
*/
|
||||
ConversionService getConversionService();
|
||||
/**
|
||||
* Returns the underlying {@link org.springframework.core.convert.ConversionService} used by the converter.
|
||||
*
|
||||
* @return never {@literal null}.
|
||||
*/
|
||||
ConversionService getConversionService();
|
||||
|
||||
}
|
||||
|
||||
@@ -27,28 +27,29 @@ import org.springframework.data.mapping.context.MappingContext;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* MappingElasticsearchConverter
|
||||
*
|
||||
* MappingElasticsearchConverter
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
|
||||
public class MappingElasticsearchConverter implements ElasticsearchConverter, ApplicationContextAware{
|
||||
public class MappingElasticsearchConverter implements ElasticsearchConverter, ApplicationContextAware {
|
||||
|
||||
private final MappingContext<? extends ElasticsearchPersistentEntity<?>,ElasticsearchPersistentProperty> mappingContext;
|
||||
private final MappingContext<? extends ElasticsearchPersistentEntity<?>, ElasticsearchPersistentProperty> mappingContext;
|
||||
private final GenericConversionService conversionService;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private ApplicationContext applicationContext;
|
||||
|
||||
public MappingElasticsearchConverter(MappingContext<? extends ElasticsearchPersistentEntity<?>,ElasticsearchPersistentProperty> mappingContext) {
|
||||
public MappingElasticsearchConverter(
|
||||
MappingContext<? extends ElasticsearchPersistentEntity<?>, ElasticsearchPersistentProperty> mappingContext) {
|
||||
Assert.notNull(mappingContext);
|
||||
this.mappingContext = mappingContext;
|
||||
this.conversionService = new DefaultConversionService();
|
||||
}
|
||||
|
||||
@Override
|
||||
public MappingContext<? extends ElasticsearchPersistentEntity<?>,ElasticsearchPersistentProperty> getMappingContext() {
|
||||
public MappingContext<? extends ElasticsearchPersistentEntity<?>, ElasticsearchPersistentProperty> getMappingContext() {
|
||||
return mappingContext;
|
||||
}
|
||||
|
||||
|
||||
@@ -16,9 +16,10 @@
|
||||
package org.springframework.data.elasticsearch.core.mapping;
|
||||
|
||||
import org.springframework.data.mapping.PersistentEntity;
|
||||
|
||||
/**
|
||||
* ElasticsearchPersistentEntity
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
@@ -26,10 +27,16 @@ import org.springframework.data.mapping.PersistentEntity;
|
||||
public interface ElasticsearchPersistentEntity<T> extends PersistentEntity<T, ElasticsearchPersistentProperty> {
|
||||
|
||||
String getIndexName();
|
||||
String getIndexType();
|
||||
short getShards();
|
||||
short getReplicas();
|
||||
String getRefreshInterval();
|
||||
String getIndexStoreType();
|
||||
ElasticsearchPersistentProperty getVersionProperty();
|
||||
|
||||
String getIndexType();
|
||||
|
||||
short getShards();
|
||||
|
||||
short getReplicas();
|
||||
|
||||
String getRefreshInterval();
|
||||
|
||||
String getIndexStoreType();
|
||||
|
||||
ElasticsearchPersistentProperty getVersionProperty();
|
||||
}
|
||||
|
||||
@@ -17,24 +17,25 @@ package org.springframework.data.elasticsearch.core.mapping;
|
||||
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.data.mapping.PersistentProperty;
|
||||
|
||||
/**
|
||||
* ElasticsearchPersistentProperty
|
||||
*
|
||||
* ElasticsearchPersistentProperty
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
|
||||
public interface ElasticsearchPersistentProperty extends PersistentProperty<ElasticsearchPersistentProperty>{
|
||||
public interface ElasticsearchPersistentProperty extends PersistentProperty<ElasticsearchPersistentProperty> {
|
||||
|
||||
String getFieldName();
|
||||
String getFieldName();
|
||||
|
||||
public enum PropertyToFieldNameConverter implements Converter<ElasticsearchPersistentProperty, String> {
|
||||
public enum PropertyToFieldNameConverter implements Converter<ElasticsearchPersistentProperty, String> {
|
||||
|
||||
INSTANCE;
|
||||
INSTANCE;
|
||||
|
||||
public String convert(ElasticsearchPersistentProperty source) {
|
||||
return source.getFieldName();
|
||||
}
|
||||
}
|
||||
public String convert(ElasticsearchPersistentProperty source) {
|
||||
return source.getFieldName();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ import java.lang.reflect.Field;
|
||||
|
||||
/**
|
||||
* SimpleElasticsearchMappingContext
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
|
||||
@@ -33,81 +33,82 @@ import static org.springframework.util.StringUtils.hasText;
|
||||
|
||||
/**
|
||||
* Elasticsearch specific {@link org.springframework.data.mapping.PersistentEntity} implementation holding
|
||||
*
|
||||
*
|
||||
* @param <T>
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
public class SimpleElasticsearchPersistentEntity<T> extends BasicPersistentEntity<T, ElasticsearchPersistentProperty> implements
|
||||
ElasticsearchPersistentEntity<T>, ApplicationContextAware {
|
||||
public class SimpleElasticsearchPersistentEntity<T> extends BasicPersistentEntity<T, ElasticsearchPersistentProperty>
|
||||
implements ElasticsearchPersistentEntity<T>, ApplicationContextAware {
|
||||
|
||||
private final StandardEvaluationContext context;
|
||||
private String indexName;
|
||||
private String indexType;
|
||||
private short shards;
|
||||
private short replicas;
|
||||
private String refreshInterval;
|
||||
private String indexStoreType;
|
||||
private final StandardEvaluationContext context;
|
||||
private String indexName;
|
||||
private String indexType;
|
||||
private short shards;
|
||||
private short replicas;
|
||||
private String refreshInterval;
|
||||
private String indexStoreType;
|
||||
|
||||
public SimpleElasticsearchPersistentEntity(TypeInformation<T> typeInformation) {
|
||||
super(typeInformation);
|
||||
this.context = new StandardEvaluationContext();
|
||||
Class<T> clazz = typeInformation.getType();
|
||||
if(clazz.isAnnotationPresent(Document.class)){
|
||||
Document document = clazz.getAnnotation(Document.class);
|
||||
Assert.hasText(document.indexName(), " Unknown indexName. Make sure the indexName is defined. e.g @Document(indexName=\"foo\")");
|
||||
this.indexName = typeInformation.getType().getAnnotation(Document.class).indexName();
|
||||
this.indexType = hasText(document.type())? document.type() : clazz.getSimpleName().toLowerCase(Locale.ENGLISH);
|
||||
this.shards = typeInformation.getType().getAnnotation(Document.class).shards();
|
||||
this.replicas = typeInformation.getType().getAnnotation(Document.class).replicas();
|
||||
this.refreshInterval = typeInformation.getType().getAnnotation(Document.class).refreshInterval();
|
||||
this.indexStoreType = typeInformation.getType().getAnnotation(Document.class).indexStoreType();
|
||||
}
|
||||
}
|
||||
public SimpleElasticsearchPersistentEntity(TypeInformation<T> typeInformation) {
|
||||
super(typeInformation);
|
||||
this.context = new StandardEvaluationContext();
|
||||
Class<T> clazz = typeInformation.getType();
|
||||
if (clazz.isAnnotationPresent(Document.class)) {
|
||||
Document document = clazz.getAnnotation(Document.class);
|
||||
Assert.hasText(document.indexName(),
|
||||
" Unknown indexName. Make sure the indexName is defined. e.g @Document(indexName=\"foo\")");
|
||||
this.indexName = typeInformation.getType().getAnnotation(Document.class).indexName();
|
||||
this.indexType = hasText(document.type()) ? document.type() : clazz.getSimpleName().toLowerCase(Locale.ENGLISH);
|
||||
this.shards = typeInformation.getType().getAnnotation(Document.class).shards();
|
||||
this.replicas = typeInformation.getType().getAnnotation(Document.class).replicas();
|
||||
this.refreshInterval = typeInformation.getType().getAnnotation(Document.class).refreshInterval();
|
||||
this.indexStoreType = typeInformation.getType().getAnnotation(Document.class).indexStoreType();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
|
||||
context.addPropertyAccessor(new BeanFactoryAccessor());
|
||||
context.setBeanResolver(new BeanFactoryResolver(applicationContext));
|
||||
context.setRootObject(applicationContext);
|
||||
}
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
|
||||
context.addPropertyAccessor(new BeanFactoryAccessor());
|
||||
context.setBeanResolver(new BeanFactoryResolver(applicationContext));
|
||||
context.setRootObject(applicationContext);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getIndexName() {
|
||||
return indexName;
|
||||
}
|
||||
@Override
|
||||
public String getIndexName() {
|
||||
return indexName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getIndexType() {
|
||||
return indexType;
|
||||
}
|
||||
@Override
|
||||
public String getIndexType() {
|
||||
return indexType;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getIndexStoreType() {
|
||||
return indexStoreType;
|
||||
}
|
||||
@Override
|
||||
public String getIndexStoreType() {
|
||||
return indexStoreType;
|
||||
}
|
||||
|
||||
@Override
|
||||
public short getShards() {
|
||||
return shards;
|
||||
}
|
||||
@Override
|
||||
public short getShards() {
|
||||
return shards;
|
||||
}
|
||||
|
||||
@Override
|
||||
public short getReplicas() {
|
||||
return replicas;
|
||||
}
|
||||
@Override
|
||||
public short getReplicas() {
|
||||
return replicas;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getRefreshInterval() {
|
||||
return refreshInterval;
|
||||
}
|
||||
@Override
|
||||
public String getRefreshInterval() {
|
||||
return refreshInterval;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addPersistentProperty(ElasticsearchPersistentProperty property) {
|
||||
super.addPersistentProperty(property);
|
||||
if(property.isVersionProperty()){
|
||||
Assert.isTrue(property.getType() == Long.class, "Version property should be Long");
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public void addPersistentProperty(ElasticsearchPersistentProperty property) {
|
||||
super.addPersistentProperty(property);
|
||||
if (property.isVersionProperty()) {
|
||||
Assert.isTrue(property.getType() == Long.class, "Version property should be Long");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,12 +27,12 @@ import java.util.Set;
|
||||
|
||||
/**
|
||||
* Elasticsearch specific {@link org.springframework.data.mapping.PersistentProperty} implementation processing
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
public class SimpleElasticsearchPersistentProperty extends AnnotationBasedPersistentProperty<ElasticsearchPersistentProperty> implements
|
||||
ElasticsearchPersistentProperty {
|
||||
public class SimpleElasticsearchPersistentProperty extends
|
||||
AnnotationBasedPersistentProperty<ElasticsearchPersistentProperty> implements ElasticsearchPersistentProperty {
|
||||
|
||||
private static final Set<Class<?>> SUPPORTED_ID_TYPES = new HashSet<Class<?>>();
|
||||
private static final Set<String> SUPPORTED_ID_PROPERTY_NAMES = new HashSet<String>();
|
||||
@@ -40,11 +40,11 @@ public class SimpleElasticsearchPersistentProperty extends AnnotationBasedPersis
|
||||
static {
|
||||
SUPPORTED_ID_TYPES.add(String.class);
|
||||
SUPPORTED_ID_PROPERTY_NAMES.add("id");
|
||||
SUPPORTED_ID_PROPERTY_NAMES.add("documentId");
|
||||
SUPPORTED_ID_PROPERTY_NAMES.add("documentId");
|
||||
}
|
||||
|
||||
public SimpleElasticsearchPersistentProperty(Field field, PropertyDescriptor propertyDescriptor,
|
||||
PersistentEntity<?, ElasticsearchPersistentProperty> owner, SimpleTypeHolder simpleTypeHolder) {
|
||||
PersistentEntity<?, ElasticsearchPersistentProperty> owner, SimpleTypeHolder simpleTypeHolder) {
|
||||
super(field, propertyDescriptor, owner, simpleTypeHolder);
|
||||
}
|
||||
|
||||
@@ -58,7 +58,7 @@ public class SimpleElasticsearchPersistentProperty extends AnnotationBasedPersis
|
||||
return super.isIdProperty() || SUPPORTED_ID_PROPERTY_NAMES.contains(getFieldName());
|
||||
}
|
||||
|
||||
@Override
|
||||
@Override
|
||||
protected Association<ElasticsearchPersistentProperty> createAssociation() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -26,77 +26,77 @@ import static org.apache.commons.collections.CollectionUtils.addAll;
|
||||
|
||||
/**
|
||||
* AbstractQuery
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
abstract class AbstractQuery implements Query{
|
||||
abstract class AbstractQuery implements Query {
|
||||
|
||||
protected Pageable pageable = DEFAULT_PAGE;
|
||||
protected Sort sort;
|
||||
protected List<String> indices = new ArrayList<String>();
|
||||
protected List<String> types = new ArrayList<String>();
|
||||
protected List<String> fields = new ArrayList<String>();
|
||||
protected Pageable pageable = DEFAULT_PAGE;
|
||||
protected Sort sort;
|
||||
protected List<String> indices = new ArrayList<String>();
|
||||
protected List<String> types = new ArrayList<String>();
|
||||
protected List<String> fields = new ArrayList<String>();
|
||||
|
||||
@Override
|
||||
public Sort getSort() {
|
||||
return this.sort;
|
||||
}
|
||||
@Override
|
||||
public Sort getSort() {
|
||||
return this.sort;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Pageable getPageable() {
|
||||
return this.pageable;
|
||||
}
|
||||
@Override
|
||||
public Pageable getPageable() {
|
||||
return this.pageable;
|
||||
}
|
||||
|
||||
@Override
|
||||
public final <T extends Query> T setPageable(Pageable pageable) {
|
||||
Assert.notNull(pageable);
|
||||
this.pageable = pageable;
|
||||
return (T) this.addSort(pageable.getSort());
|
||||
}
|
||||
@Override
|
||||
public final <T extends Query> T setPageable(Pageable pageable) {
|
||||
Assert.notNull(pageable);
|
||||
this.pageable = pageable;
|
||||
return (T) this.addSort(pageable.getSort());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addFields(String...fields) {
|
||||
addAll(this.fields, fields);
|
||||
}
|
||||
@Override
|
||||
public void addFields(String... fields) {
|
||||
addAll(this.fields, fields);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getFields() {
|
||||
return fields;
|
||||
}
|
||||
@Override
|
||||
public List<String> getFields() {
|
||||
return fields;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getIndices() {
|
||||
return indices;
|
||||
}
|
||||
@Override
|
||||
public List<String> getIndices() {
|
||||
return indices;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addIndices(String... indices) {
|
||||
addAll(this.indices,indices);
|
||||
}
|
||||
@Override
|
||||
public void addIndices(String... indices) {
|
||||
addAll(this.indices, indices);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addTypes(String... types) {
|
||||
addAll(this.types,types);
|
||||
}
|
||||
@Override
|
||||
public void addTypes(String... types) {
|
||||
addAll(this.types, types);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getTypes() {
|
||||
return types;
|
||||
}
|
||||
@Override
|
||||
public List<String> getTypes() {
|
||||
return types;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public final <T extends Query> T addSort(Sort sort) {
|
||||
if (sort == null) {
|
||||
return (T) this;
|
||||
}
|
||||
@SuppressWarnings("unchecked")
|
||||
public final <T extends Query> T addSort(Sort sort) {
|
||||
if (sort == null) {
|
||||
return (T) this;
|
||||
}
|
||||
|
||||
if (this.sort == null) {
|
||||
this.sort = sort;
|
||||
} else {
|
||||
this.sort = this.sort.and(sort);
|
||||
}
|
||||
if (this.sort == null) {
|
||||
this.sort = sort;
|
||||
} else {
|
||||
this.sort = this.sort.and(sort);
|
||||
}
|
||||
|
||||
return (T) this;
|
||||
}
|
||||
return (T) this;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ import org.springframework.util.Assert;
|
||||
/**
|
||||
* Criteria is the central class when constructing queries. It follows more or less a fluent API style, which allows to
|
||||
* easily chain together multiple criteria.
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
@@ -251,11 +251,10 @@ public class Criteria {
|
||||
* @return
|
||||
*/
|
||||
public Criteria fuzzy(String s) {
|
||||
criteria.add(new CriteriaEntry(OperationKey.FUZZY, s));
|
||||
return this;
|
||||
criteria.add(new CriteriaEntry(OperationKey.FUZZY, s));
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Crates new CriteriaEntry allowing native elasticsearch expressions
|
||||
*
|
||||
@@ -342,11 +341,10 @@ public class Criteria {
|
||||
*/
|
||||
public Criteria in(Iterable<?> values) {
|
||||
Assert.notNull(values, "Collection of 'in' values must not be null");
|
||||
criteria.add(new CriteriaEntry(OperationKey.IN, values));
|
||||
criteria.add(new CriteriaEntry(OperationKey.IN, values));
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
private void assertNoBlankInWildcardedQuery(String searchString, boolean leadingWildcard, boolean trailingWildcard) {
|
||||
if (StringUtils.contains(searchString, CRITERIA_VALUE_SEPERATOR)) {
|
||||
throw new InvalidDataAccessApiUsageException("Cannot constructQuery '" + (leadingWildcard ? "*" : "") + "\""
|
||||
@@ -384,13 +382,13 @@ public class Criteria {
|
||||
return this.negating;
|
||||
}
|
||||
|
||||
public boolean isAnd(){
|
||||
return AND_OPERATOR == getConjunctionOperator();
|
||||
}
|
||||
public boolean isAnd() {
|
||||
return AND_OPERATOR == getConjunctionOperator();
|
||||
}
|
||||
|
||||
public boolean isOr(){
|
||||
return OR_OPERATOR == getConjunctionOperator();
|
||||
}
|
||||
public boolean isOr() {
|
||||
return OR_OPERATOR == getConjunctionOperator();
|
||||
}
|
||||
|
||||
public float getBoost() {
|
||||
return this.boost;
|
||||
@@ -431,7 +429,7 @@ public class Criteria {
|
||||
|
||||
public static class CriteriaEntry {
|
||||
|
||||
private OperationKey key;
|
||||
private OperationKey key;
|
||||
private Object value;
|
||||
|
||||
CriteriaEntry(OperationKey key, Object value) {
|
||||
|
||||
@@ -15,67 +15,67 @@
|
||||
*/
|
||||
package org.springframework.data.elasticsearch.core.query;
|
||||
|
||||
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* CriteriaQuery
|
||||
*
|
||||
* CriteriaQuery
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
public class CriteriaQuery extends AbstractQuery{
|
||||
public class CriteriaQuery extends AbstractQuery {
|
||||
|
||||
private Criteria criteria;
|
||||
private CriteriaQuery() {
|
||||
}
|
||||
private Criteria criteria;
|
||||
|
||||
public CriteriaQuery(Criteria criteria) {
|
||||
this(criteria, null);
|
||||
}
|
||||
private CriteriaQuery() {
|
||||
}
|
||||
|
||||
public CriteriaQuery(Criteria criteria, Pageable pageable) {
|
||||
this.criteria = criteria;
|
||||
this.pageable = pageable;
|
||||
if (pageable != null) {
|
||||
this.addSort(pageable.getSort());
|
||||
}
|
||||
}
|
||||
public CriteriaQuery(Criteria criteria) {
|
||||
this(criteria, null);
|
||||
}
|
||||
|
||||
public static final Query fromQuery(CriteriaQuery source) {
|
||||
return fromQuery(source, new CriteriaQuery());
|
||||
}
|
||||
public CriteriaQuery(Criteria criteria, Pageable pageable) {
|
||||
this.criteria = criteria;
|
||||
this.pageable = pageable;
|
||||
if (pageable != null) {
|
||||
this.addSort(pageable.getSort());
|
||||
}
|
||||
}
|
||||
|
||||
public static <T extends CriteriaQuery> T fromQuery(CriteriaQuery source, T destination) {
|
||||
if (source == null || destination == null) {
|
||||
return null;
|
||||
}
|
||||
public static final Query fromQuery(CriteriaQuery source) {
|
||||
return fromQuery(source, new CriteriaQuery());
|
||||
}
|
||||
|
||||
if (source.getCriteria() != null) {
|
||||
destination.addCriteria(source.getCriteria());
|
||||
}
|
||||
public static <T extends CriteriaQuery> T fromQuery(CriteriaQuery source, T destination) {
|
||||
if (source == null || destination == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (source.getSort() != null) {
|
||||
destination.addSort(source.getSort());
|
||||
}
|
||||
if (source.getCriteria() != null) {
|
||||
destination.addCriteria(source.getCriteria());
|
||||
}
|
||||
|
||||
return destination;
|
||||
}
|
||||
if (source.getSort() != null) {
|
||||
destination.addSort(source.getSort());
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public final <T extends CriteriaQuery> T addCriteria(Criteria criteria) {
|
||||
Assert.notNull(criteria, "Cannot add null criteria.");
|
||||
if (this.criteria == null) {
|
||||
this.criteria = criteria;
|
||||
} else {
|
||||
this.criteria.and(criteria);
|
||||
}
|
||||
return (T) this;
|
||||
}
|
||||
return destination;
|
||||
}
|
||||
|
||||
public Criteria getCriteria() {
|
||||
return this.criteria;
|
||||
}
|
||||
@SuppressWarnings("unchecked")
|
||||
public final <T extends CriteriaQuery> T addCriteria(Criteria criteria) {
|
||||
Assert.notNull(criteria, "Cannot add null criteria.");
|
||||
if (this.criteria == null) {
|
||||
this.criteria = criteria;
|
||||
} else {
|
||||
this.criteria.and(criteria);
|
||||
}
|
||||
return (T) this;
|
||||
}
|
||||
|
||||
public Criteria getCriteria() {
|
||||
return this.criteria;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -15,23 +15,23 @@
|
||||
*/
|
||||
package org.springframework.data.elasticsearch.core.query;
|
||||
|
||||
|
||||
import org.elasticsearch.index.query.QueryBuilder;
|
||||
|
||||
/**
|
||||
* DeleteQuery
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
public class DeleteQuery{
|
||||
public class DeleteQuery {
|
||||
|
||||
private QueryBuilder query;
|
||||
private QueryBuilder query;
|
||||
|
||||
public QueryBuilder getQuery() {
|
||||
return query;
|
||||
}
|
||||
public QueryBuilder getQuery() {
|
||||
return query;
|
||||
}
|
||||
|
||||
public void setQuery(QueryBuilder query) {
|
||||
this.query = query;
|
||||
}
|
||||
public void setQuery(QueryBuilder query) {
|
||||
this.query = query;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ package org.springframework.data.elasticsearch.core.query;
|
||||
|
||||
/**
|
||||
* Defines a Field that can be used within a Criteria.
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
|
||||
@@ -16,20 +16,20 @@
|
||||
package org.springframework.data.elasticsearch.core.query;
|
||||
|
||||
/**
|
||||
* GetQuery
|
||||
*
|
||||
* GetQuery
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
public class GetQuery{
|
||||
public class GetQuery {
|
||||
|
||||
private String id;
|
||||
private String id;
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,56 +17,56 @@ package org.springframework.data.elasticsearch.core.query;
|
||||
|
||||
/**
|
||||
* IndexQuery
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
|
||||
public class IndexQuery{
|
||||
public class IndexQuery {
|
||||
|
||||
private String id;
|
||||
private Object object;
|
||||
private Long version;
|
||||
private String indexName;
|
||||
private String type;
|
||||
private String id;
|
||||
private Object object;
|
||||
private Long version;
|
||||
private String indexName;
|
||||
private String type;
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Object getObject() {
|
||||
return object;
|
||||
}
|
||||
public Object getObject() {
|
||||
return object;
|
||||
}
|
||||
|
||||
public void setObject(Object object) {
|
||||
this.object = object;
|
||||
}
|
||||
public void setObject(Object object) {
|
||||
this.object = object;
|
||||
}
|
||||
|
||||
public Long getVersion() {
|
||||
return version;
|
||||
}
|
||||
public Long getVersion() {
|
||||
return version;
|
||||
}
|
||||
|
||||
public void setVersion(Long version) {
|
||||
this.version = version;
|
||||
}
|
||||
public void setVersion(Long version) {
|
||||
this.version = version;
|
||||
}
|
||||
|
||||
public String getIndexName() {
|
||||
return indexName;
|
||||
}
|
||||
public String getIndexName() {
|
||||
return indexName;
|
||||
}
|
||||
|
||||
public void setIndexName(String indexName) {
|
||||
this.indexName = indexName;
|
||||
}
|
||||
public void setIndexName(String indexName) {
|
||||
this.indexName = indexName;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,164 +25,164 @@ import static org.springframework.data.elasticsearch.core.query.Query.DEFAULT_PA
|
||||
|
||||
/**
|
||||
* MoreLikeThisQuery
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
|
||||
public class MoreLikeThisQuery {
|
||||
|
||||
private String id;
|
||||
private String indexName;
|
||||
private String type;
|
||||
private List<String> searchIndices = new ArrayList<String>();
|
||||
private List<String> searchTypes = new ArrayList<String>();
|
||||
private List<String> fields = new ArrayList<String>();
|
||||
private String routing;
|
||||
private Float percentTermsToMatch;
|
||||
private Integer minTermFreq;
|
||||
private Integer maxQueryTerms;
|
||||
private List<String> stopWords = new ArrayList<String>();
|
||||
private Integer minDocFreq;
|
||||
private Integer maxDocFreq;
|
||||
private Integer minWordLen;
|
||||
private Integer maxWordLen;
|
||||
private Float boostTerms;
|
||||
private Pageable pageable = DEFAULT_PAGE;
|
||||
private String id;
|
||||
private String indexName;
|
||||
private String type;
|
||||
private List<String> searchIndices = new ArrayList<String>();
|
||||
private List<String> searchTypes = new ArrayList<String>();
|
||||
private List<String> fields = new ArrayList<String>();
|
||||
private String routing;
|
||||
private Float percentTermsToMatch;
|
||||
private Integer minTermFreq;
|
||||
private Integer maxQueryTerms;
|
||||
private List<String> stopWords = new ArrayList<String>();
|
||||
private Integer minDocFreq;
|
||||
private Integer maxDocFreq;
|
||||
private Integer minWordLen;
|
||||
private Integer maxWordLen;
|
||||
private Float boostTerms;
|
||||
private Pageable pageable = DEFAULT_PAGE;
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getIndexName() {
|
||||
return indexName;
|
||||
}
|
||||
public String getIndexName() {
|
||||
return indexName;
|
||||
}
|
||||
|
||||
public void setIndexName(String indexName) {
|
||||
this.indexName = indexName;
|
||||
}
|
||||
public void setIndexName(String indexName) {
|
||||
this.indexName = indexName;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public List<String> getSearchIndices() {
|
||||
return searchIndices;
|
||||
}
|
||||
public List<String> getSearchIndices() {
|
||||
return searchIndices;
|
||||
}
|
||||
|
||||
public void addSearchIndices(String...searchIndices) {
|
||||
addAll(this.searchIndices, searchIndices);
|
||||
}
|
||||
public void addSearchIndices(String... searchIndices) {
|
||||
addAll(this.searchIndices, searchIndices);
|
||||
}
|
||||
|
||||
public List<String> getSearchTypes() {
|
||||
return searchTypes;
|
||||
}
|
||||
public List<String> getSearchTypes() {
|
||||
return searchTypes;
|
||||
}
|
||||
|
||||
public void addSearchTypes(String...searchTypes) {
|
||||
addAll(this.searchTypes, searchTypes);
|
||||
}
|
||||
public void addSearchTypes(String... searchTypes) {
|
||||
addAll(this.searchTypes, searchTypes);
|
||||
}
|
||||
|
||||
public List<String> getFields() {
|
||||
return fields;
|
||||
}
|
||||
public List<String> getFields() {
|
||||
return fields;
|
||||
}
|
||||
|
||||
public void addFields(String...fields) {
|
||||
addAll(this.fields,fields);
|
||||
}
|
||||
public void addFields(String... fields) {
|
||||
addAll(this.fields, fields);
|
||||
}
|
||||
|
||||
public String getRouting() {
|
||||
return routing;
|
||||
}
|
||||
public String getRouting() {
|
||||
return routing;
|
||||
}
|
||||
|
||||
public void setRouting(String routing) {
|
||||
this.routing = routing;
|
||||
}
|
||||
public void setRouting(String routing) {
|
||||
this.routing = routing;
|
||||
}
|
||||
|
||||
public Float getPercentTermsToMatch() {
|
||||
return percentTermsToMatch;
|
||||
}
|
||||
public Float getPercentTermsToMatch() {
|
||||
return percentTermsToMatch;
|
||||
}
|
||||
|
||||
public void setPercentTermsToMatch(Float percentTermsToMatch) {
|
||||
this.percentTermsToMatch = percentTermsToMatch;
|
||||
}
|
||||
public void setPercentTermsToMatch(Float percentTermsToMatch) {
|
||||
this.percentTermsToMatch = percentTermsToMatch;
|
||||
}
|
||||
|
||||
public Integer getMinTermFreq() {
|
||||
return minTermFreq;
|
||||
}
|
||||
public Integer getMinTermFreq() {
|
||||
return minTermFreq;
|
||||
}
|
||||
|
||||
public void setMinTermFreq(Integer minTermFreq) {
|
||||
this.minTermFreq = minTermFreq;
|
||||
}
|
||||
public void setMinTermFreq(Integer minTermFreq) {
|
||||
this.minTermFreq = minTermFreq;
|
||||
}
|
||||
|
||||
public Integer getMaxQueryTerms() {
|
||||
return maxQueryTerms;
|
||||
}
|
||||
public Integer getMaxQueryTerms() {
|
||||
return maxQueryTerms;
|
||||
}
|
||||
|
||||
public void setMaxQueryTerms(Integer maxQueryTerms) {
|
||||
this.maxQueryTerms = maxQueryTerms;
|
||||
}
|
||||
public void setMaxQueryTerms(Integer maxQueryTerms) {
|
||||
this.maxQueryTerms = maxQueryTerms;
|
||||
}
|
||||
|
||||
public List<String> getStopWords() {
|
||||
return stopWords;
|
||||
}
|
||||
public List<String> getStopWords() {
|
||||
return stopWords;
|
||||
}
|
||||
|
||||
public void addStopWords(String...stopWords) {
|
||||
addAll(this.stopWords,stopWords);
|
||||
}
|
||||
public void addStopWords(String... stopWords) {
|
||||
addAll(this.stopWords, stopWords);
|
||||
}
|
||||
|
||||
public Integer getMinDocFreq() {
|
||||
return minDocFreq;
|
||||
}
|
||||
public Integer getMinDocFreq() {
|
||||
return minDocFreq;
|
||||
}
|
||||
|
||||
public void setMinDocFreq(Integer minDocFreq) {
|
||||
this.minDocFreq = minDocFreq;
|
||||
}
|
||||
public void setMinDocFreq(Integer minDocFreq) {
|
||||
this.minDocFreq = minDocFreq;
|
||||
}
|
||||
|
||||
public Integer getMaxDocFreq() {
|
||||
return maxDocFreq;
|
||||
}
|
||||
public Integer getMaxDocFreq() {
|
||||
return maxDocFreq;
|
||||
}
|
||||
|
||||
public void setMaxDocFreq(Integer maxDocFreq) {
|
||||
this.maxDocFreq = maxDocFreq;
|
||||
}
|
||||
public void setMaxDocFreq(Integer maxDocFreq) {
|
||||
this.maxDocFreq = maxDocFreq;
|
||||
}
|
||||
|
||||
public Integer getMinWordLen() {
|
||||
return minWordLen;
|
||||
}
|
||||
public Integer getMinWordLen() {
|
||||
return minWordLen;
|
||||
}
|
||||
|
||||
public void setMinWordLen(Integer minWordLen) {
|
||||
this.minWordLen = minWordLen;
|
||||
}
|
||||
public void setMinWordLen(Integer minWordLen) {
|
||||
this.minWordLen = minWordLen;
|
||||
}
|
||||
|
||||
public Integer getMaxWordLen() {
|
||||
return maxWordLen;
|
||||
}
|
||||
public Integer getMaxWordLen() {
|
||||
return maxWordLen;
|
||||
}
|
||||
|
||||
public void setMaxWordLen(Integer maxWordLen) {
|
||||
this.maxWordLen = maxWordLen;
|
||||
}
|
||||
public void setMaxWordLen(Integer maxWordLen) {
|
||||
this.maxWordLen = maxWordLen;
|
||||
}
|
||||
|
||||
public Float getBoostTerms() {
|
||||
return boostTerms;
|
||||
}
|
||||
public Float getBoostTerms() {
|
||||
return boostTerms;
|
||||
}
|
||||
|
||||
public void setBoostTerms(Float boostTerms) {
|
||||
this.boostTerms = boostTerms;
|
||||
}
|
||||
public void setBoostTerms(Float boostTerms) {
|
||||
this.boostTerms = boostTerms;
|
||||
}
|
||||
|
||||
public Pageable getPageable() {
|
||||
return pageable;
|
||||
}
|
||||
public Pageable getPageable() {
|
||||
return pageable;
|
||||
}
|
||||
|
||||
public void setPageable(Pageable pageable) {
|
||||
this.pageable = pageable;
|
||||
}
|
||||
public void setPageable(Pageable pageable) {
|
||||
this.pageable = pageable;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,40 +15,38 @@
|
||||
*/
|
||||
package org.springframework.data.elasticsearch.core.query;
|
||||
|
||||
|
||||
import org.elasticsearch.index.query.FilterBuilder;
|
||||
import org.elasticsearch.index.query.QueryBuilder;
|
||||
import org.elasticsearch.search.sort.SortBuilder;
|
||||
|
||||
/**
|
||||
* NativeSearchQuery
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
* @author Artur Konczak
|
||||
*/
|
||||
public class NativeSearchQuery extends AbstractQuery implements SearchQuery {
|
||||
|
||||
private QueryBuilder query;
|
||||
private FilterBuilder filter;
|
||||
private SortBuilder sort;
|
||||
private QueryBuilder query;
|
||||
private FilterBuilder filter;
|
||||
private SortBuilder sort;
|
||||
|
||||
public NativeSearchQuery(QueryBuilder query, FilterBuilder filter, SortBuilder sort) {
|
||||
this.query = query;
|
||||
this.filter = filter;
|
||||
this.sort = sort;
|
||||
}
|
||||
public NativeSearchQuery(QueryBuilder query, FilterBuilder filter, SortBuilder sort) {
|
||||
this.query = query;
|
||||
this.filter = filter;
|
||||
this.sort = sort;
|
||||
}
|
||||
|
||||
public QueryBuilder getQuery() {
|
||||
return query;
|
||||
}
|
||||
public QueryBuilder getQuery() {
|
||||
return query;
|
||||
}
|
||||
|
||||
public FilterBuilder getFilter() {
|
||||
return filter;
|
||||
}
|
||||
|
||||
public FilterBuilder getFilter() {
|
||||
return filter;
|
||||
}
|
||||
|
||||
public SortBuilder getElasticsearchSort() {
|
||||
return sort;
|
||||
}
|
||||
public SortBuilder getElasticsearchSort() {
|
||||
return sort;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ import org.springframework.data.domain.Pageable;
|
||||
|
||||
/**
|
||||
* NativeSearchQuery
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
* @author Artur Konczak
|
||||
@@ -30,63 +30,63 @@ import org.springframework.data.domain.Pageable;
|
||||
|
||||
public class NativeSearchQueryBuilder {
|
||||
|
||||
private QueryBuilder queryBuilder;
|
||||
private FilterBuilder filterBuilder;
|
||||
private SortBuilder sortBuilder;
|
||||
private Pageable pageable;
|
||||
private String[] indices;
|
||||
private String[] types;
|
||||
private String[] fields;
|
||||
private QueryBuilder queryBuilder;
|
||||
private FilterBuilder filterBuilder;
|
||||
private SortBuilder sortBuilder;
|
||||
private Pageable pageable;
|
||||
private String[] indices;
|
||||
private String[] types;
|
||||
private String[] fields;
|
||||
|
||||
public NativeSearchQueryBuilder withQuery(QueryBuilder queryBuilder){
|
||||
this.queryBuilder = queryBuilder;
|
||||
return this;
|
||||
}
|
||||
public NativeSearchQueryBuilder withQuery(QueryBuilder queryBuilder) {
|
||||
this.queryBuilder = queryBuilder;
|
||||
return this;
|
||||
}
|
||||
|
||||
public NativeSearchQueryBuilder withFilter(FilterBuilder filterBuilder){
|
||||
this.filterBuilder = filterBuilder;
|
||||
return this;
|
||||
}
|
||||
public NativeSearchQueryBuilder withFilter(FilterBuilder filterBuilder) {
|
||||
this.filterBuilder = filterBuilder;
|
||||
return this;
|
||||
}
|
||||
|
||||
public NativeSearchQueryBuilder withSort(SortBuilder sortBuilder){
|
||||
this.sortBuilder = sortBuilder;
|
||||
return this;
|
||||
}
|
||||
public NativeSearchQueryBuilder withSort(SortBuilder sortBuilder) {
|
||||
this.sortBuilder = sortBuilder;
|
||||
return this;
|
||||
}
|
||||
|
||||
public NativeSearchQueryBuilder withPageable(Pageable pageable){
|
||||
this.pageable = pageable;
|
||||
return this;
|
||||
}
|
||||
public NativeSearchQueryBuilder withPageable(Pageable pageable) {
|
||||
this.pageable = pageable;
|
||||
return this;
|
||||
}
|
||||
|
||||
public NativeSearchQueryBuilder withIndices(String... indices){
|
||||
this.indices = indices;
|
||||
return this;
|
||||
}
|
||||
public NativeSearchQueryBuilder withIndices(String... indices) {
|
||||
this.indices = indices;
|
||||
return this;
|
||||
}
|
||||
|
||||
public NativeSearchQueryBuilder withTypes(String... types){
|
||||
this.types = types;
|
||||
return this;
|
||||
}
|
||||
public NativeSearchQueryBuilder withTypes(String... types) {
|
||||
this.types = types;
|
||||
return this;
|
||||
}
|
||||
|
||||
public NativeSearchQueryBuilder withFields(String... fields){
|
||||
this.fields = fields;
|
||||
return this;
|
||||
}
|
||||
public NativeSearchQueryBuilder withFields(String... fields) {
|
||||
this.fields = fields;
|
||||
return this;
|
||||
}
|
||||
|
||||
public NativeSearchQuery build(){
|
||||
NativeSearchQuery nativeSearchQuery = new NativeSearchQuery(queryBuilder,filterBuilder,sortBuilder);
|
||||
if(pageable != null){
|
||||
nativeSearchQuery.setPageable(pageable);
|
||||
}
|
||||
if(indices != null) {
|
||||
nativeSearchQuery.addIndices(indices);
|
||||
}
|
||||
if(types != null) {
|
||||
nativeSearchQuery.addTypes(types);
|
||||
}
|
||||
if(fields != null) {
|
||||
nativeSearchQuery.addFields(fields);
|
||||
}
|
||||
return nativeSearchQuery;
|
||||
}
|
||||
public NativeSearchQuery build() {
|
||||
NativeSearchQuery nativeSearchQuery = new NativeSearchQuery(queryBuilder, filterBuilder, sortBuilder);
|
||||
if (pageable != null) {
|
||||
nativeSearchQuery.setPageable(pageable);
|
||||
}
|
||||
if (indices != null) {
|
||||
nativeSearchQuery.addIndices(indices);
|
||||
}
|
||||
if (types != null) {
|
||||
nativeSearchQuery.addTypes(types);
|
||||
}
|
||||
if (fields != null) {
|
||||
nativeSearchQuery.addFields(fields);
|
||||
}
|
||||
return nativeSearchQuery;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,99 +15,97 @@
|
||||
*/
|
||||
package org.springframework.data.elasticsearch.core.query;
|
||||
|
||||
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Query
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
public interface Query {
|
||||
|
||||
public static final int DEFAULT_PAGE_SIZE = 10;
|
||||
public static final Pageable DEFAULT_PAGE = new PageRequest(0, DEFAULT_PAGE_SIZE);
|
||||
public static final int DEFAULT_PAGE_SIZE = 10;
|
||||
public static final Pageable DEFAULT_PAGE = new PageRequest(0, DEFAULT_PAGE_SIZE);
|
||||
|
||||
/**
|
||||
* restrict result to entries on given page. Corresponds to the 'start' and 'rows' parameter in elasticsearch
|
||||
*
|
||||
* @param pageable
|
||||
* @return
|
||||
*/
|
||||
<T extends Query> T setPageable(Pageable pageable);
|
||||
|
||||
/**
|
||||
* restrict result to entries on given page. Corresponds to the 'start' and 'rows' parameter in elasticsearch
|
||||
*
|
||||
* @param pageable
|
||||
* @return
|
||||
*/
|
||||
<T extends Query> T setPageable(Pageable pageable);
|
||||
/**
|
||||
* Get filter queries if defined
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
// List<FilterQuery> getFilterQueries();
|
||||
|
||||
/**
|
||||
* Get page settings if defined
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
Pageable getPageable();
|
||||
|
||||
/**
|
||||
* Add {@link org.springframework.data.domain.Sort} to query
|
||||
*
|
||||
* @param sort
|
||||
* @return
|
||||
*/
|
||||
<T extends Query> T addSort(Sort sort);
|
||||
|
||||
/**
|
||||
* Get filter queries if defined
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
//List<FilterQuery> getFilterQueries();
|
||||
/**
|
||||
* @return null if not set
|
||||
*/
|
||||
Sort getSort();
|
||||
|
||||
/**
|
||||
* Get page settings if defined
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
Pageable getPageable();
|
||||
/**
|
||||
* Get Indices to be searched
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
List<String> getIndices();
|
||||
|
||||
/**
|
||||
* Add Indices to be added as part of search request
|
||||
*
|
||||
* @param indices
|
||||
*/
|
||||
void addIndices(String... indices);
|
||||
|
||||
/**
|
||||
* Add types to be searched
|
||||
*
|
||||
* @param types
|
||||
*/
|
||||
void addTypes(String... types);
|
||||
|
||||
/**
|
||||
* Add {@link org.springframework.data.domain.Sort} to query
|
||||
*
|
||||
* @param sort
|
||||
* @return
|
||||
*/
|
||||
<T extends Query> T addSort(Sort sort);
|
||||
/**
|
||||
* Get types to be searched
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
List<String> getTypes();
|
||||
|
||||
/**
|
||||
* @return null if not set
|
||||
*/
|
||||
Sort getSort();
|
||||
/**
|
||||
* Add fields to be added as part of search request
|
||||
*
|
||||
* @param fields
|
||||
*/
|
||||
void addFields(String... fields);
|
||||
|
||||
|
||||
/**
|
||||
* Get Indices to be searched
|
||||
* @return
|
||||
*/
|
||||
List<String> getIndices();
|
||||
|
||||
|
||||
/**
|
||||
* Add Indices to be added as part of search request
|
||||
* @param indices
|
||||
*/
|
||||
void addIndices(String...indices);
|
||||
|
||||
/**
|
||||
* Add types to be searched
|
||||
* @param types
|
||||
*/
|
||||
void addTypes(String...types);
|
||||
|
||||
/**
|
||||
* Get types to be searched
|
||||
* @return
|
||||
*/
|
||||
List<String> getTypes();
|
||||
|
||||
/**
|
||||
* Add fields to be added as part of search request
|
||||
* @param fields
|
||||
*/
|
||||
void addFields(String...fields);
|
||||
|
||||
|
||||
/**
|
||||
* Get fields to be returned as part of search request
|
||||
* @return
|
||||
*/
|
||||
List<String> getFields();
|
||||
/**
|
||||
* Get fields to be returned as part of search request
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
List<String> getFields();
|
||||
}
|
||||
|
||||
@@ -18,15 +18,18 @@ package org.springframework.data.elasticsearch.core.query;
|
||||
import org.elasticsearch.index.query.FilterBuilder;
|
||||
import org.elasticsearch.index.query.QueryBuilder;
|
||||
import org.elasticsearch.search.sort.SortBuilder;
|
||||
|
||||
/**
|
||||
* NativeSearchQuery
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
* @author Artur Konczak
|
||||
*/
|
||||
public interface SearchQuery extends Query {
|
||||
QueryBuilder getQuery();
|
||||
FilterBuilder getFilter();
|
||||
SortBuilder getElasticsearchSort();
|
||||
QueryBuilder getQuery();
|
||||
|
||||
FilterBuilder getFilter();
|
||||
|
||||
SortBuilder getElasticsearchSort();
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ package org.springframework.data.elasticsearch.core.query;
|
||||
|
||||
/**
|
||||
* The most trivial implementation of a Field
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
|
||||
@@ -15,38 +15,36 @@
|
||||
*/
|
||||
package org.springframework.data.elasticsearch.core.query;
|
||||
|
||||
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
|
||||
/**
|
||||
* StringQuery
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
public class StringQuery extends AbstractQuery{
|
||||
public class StringQuery extends AbstractQuery {
|
||||
|
||||
private String source;
|
||||
private String source;
|
||||
|
||||
public StringQuery(String source) {
|
||||
this.source = source;
|
||||
}
|
||||
public StringQuery(String source) {
|
||||
this.source = source;
|
||||
}
|
||||
|
||||
public StringQuery(String source, Pageable pageable) {
|
||||
this.source = source;
|
||||
this.pageable = pageable;
|
||||
}
|
||||
public StringQuery(String source, Pageable pageable) {
|
||||
this.source = source;
|
||||
this.pageable = pageable;
|
||||
}
|
||||
|
||||
public StringQuery(String source, Pageable pageable, Sort sort) {
|
||||
this.pageable = pageable;
|
||||
this.sort = sort;
|
||||
this.source = source;
|
||||
}
|
||||
public StringQuery(String source, Pageable pageable, Sort sort) {
|
||||
this.pageable = pageable;
|
||||
this.sort = sort;
|
||||
this.source = source;
|
||||
}
|
||||
|
||||
|
||||
public String getSource() {
|
||||
return source;
|
||||
}
|
||||
public String getSource() {
|
||||
return source;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -23,12 +23,12 @@ import java.util.List;
|
||||
/**
|
||||
* @param <T>
|
||||
* @param <ID>
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
public interface ElasticsearchCrudRepository<T, ID extends Serializable> extends PagingAndSortingRepository<T, ID> {
|
||||
|
||||
<S extends T> List<S> save(List<S> entities);
|
||||
<S extends T> List<S> save(List<S> entities);
|
||||
|
||||
}
|
||||
|
||||
@@ -26,20 +26,20 @@ import java.io.Serializable;
|
||||
/**
|
||||
* @param <T>
|
||||
* @param <ID>
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
@NoRepositoryBean
|
||||
public interface ElasticsearchRepository<T, ID extends Serializable> extends ElasticsearchCrudRepository<T,ID> {
|
||||
public interface ElasticsearchRepository<T, ID extends Serializable> extends ElasticsearchCrudRepository<T, ID> {
|
||||
|
||||
<S extends T> S index(S entity);
|
||||
<S extends T> S index(S entity);
|
||||
|
||||
Iterable<T> search(QueryBuilder query);
|
||||
Iterable<T> search(QueryBuilder query);
|
||||
|
||||
Page<T> search(QueryBuilder query, Pageable pageable);
|
||||
Page<T> search(QueryBuilder query, Pageable pageable);
|
||||
|
||||
Page<T> search(SearchQuery searchQuery);
|
||||
Page<T> search(SearchQuery searchQuery);
|
||||
|
||||
Page<T> searchSimilar(T entity, SearchQuery searchQuery);
|
||||
Page<T> searchSimilar(T entity, SearchQuery searchQuery);
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ import java.util.Set;
|
||||
|
||||
/**
|
||||
* Uses CdiRepositoryBean to create ElasticsearchRepository instances.
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
@@ -36,8 +36,8 @@ public class ElasticsearchRepositoryBean<T> extends CdiRepositoryBean<T> {
|
||||
|
||||
private final Bean<ElasticsearchOperations> elasticsearchOperationsBean;
|
||||
|
||||
public ElasticsearchRepositoryBean(Bean<ElasticsearchOperations> operations, Set<Annotation> qualifiers, Class<T> repositoryType,
|
||||
BeanManager beanManager) {
|
||||
public ElasticsearchRepositoryBean(Bean<ElasticsearchOperations> operations, Set<Annotation> qualifiers,
|
||||
Class<T> repositoryType, BeanManager beanManager) {
|
||||
super(qualifiers, repositoryType, beanManager);
|
||||
|
||||
Assert.notNull(operations, "Cannot create repository with 'null' for ElasticsearchOperations.");
|
||||
@@ -46,7 +46,8 @@ public class ElasticsearchRepositoryBean<T> extends CdiRepositoryBean<T> {
|
||||
|
||||
@Override
|
||||
protected T create(CreationalContext<T> creationalContext, Class<T> repositoryType) {
|
||||
ElasticsearchOperations elasticsearchOperations = getDependencyInstance(elasticsearchOperationsBean, ElasticsearchOperations.class);
|
||||
ElasticsearchOperations elasticsearchOperations = getDependencyInstance(elasticsearchOperationsBean,
|
||||
ElasticsearchOperations.class);
|
||||
return new ElasticsearchRepositoryFactory(elasticsearchOperations).getRepository(repositoryType);
|
||||
}
|
||||
|
||||
|
||||
@@ -33,7 +33,7 @@ import java.util.Set;
|
||||
|
||||
/**
|
||||
* ElasticsearchRepositoryExtension
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
@@ -53,24 +53,25 @@ public class ElasticsearchRepositoryExtension extends CdiRepositoryExtensionSupp
|
||||
}
|
||||
|
||||
void afterBeanDiscovery(@Observes AfterBeanDiscovery afterBeanDiscovery, BeanManager beanManager) {
|
||||
for (Entry<Class<?>, Set<Annotation>> entry : getRepositoryTypes()) {
|
||||
for (Entry<Class<?>, Set<Annotation>> entry : getRepositoryTypes()) {
|
||||
|
||||
Class<?> repositoryType = entry.getKey();
|
||||
Set<Annotation> qualifiers = entry.getValue();
|
||||
|
||||
Bean<?> repositoryBean = createRepositoryBean(repositoryType, qualifiers, beanManager);
|
||||
afterBeanDiscovery.addBean(repositoryBean);
|
||||
afterBeanDiscovery.addBean(repositoryBean);
|
||||
}
|
||||
}
|
||||
|
||||
private <T> Bean<T> createRepositoryBean(Class<T> repositoryType, Set<Annotation> qualifiers, BeanManager beanManager) {
|
||||
Bean<ElasticsearchOperations> elasticsearchOperationsBean = this.elasticsearchOperationsMap.get(qualifiers.toString());
|
||||
Bean<ElasticsearchOperations> elasticsearchOperationsBean = this.elasticsearchOperationsMap.get(qualifiers
|
||||
.toString());
|
||||
|
||||
if (elasticsearchOperationsBean == null) {
|
||||
throw new UnsatisfiedResolutionException(String.format("Unable to resolve a bean for '%s' with qualifiers %s.",
|
||||
ElasticsearchOperations.class.getName(), qualifiers));
|
||||
ElasticsearchOperations.class.getName(), qualifiers));
|
||||
}
|
||||
return new ElasticsearchRepositoryBean<T>(elasticsearchOperationsBean, qualifiers, repositoryType, beanManager);
|
||||
return new ElasticsearchRepositoryBean<T>(elasticsearchOperationsBean, qualifiers, repositoryType, beanManager);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -21,9 +21,9 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi
|
||||
import java.lang.annotation.Annotation;
|
||||
|
||||
/**
|
||||
* {@link org.springframework.context.annotation.ImportBeanDefinitionRegistrar} implementation to trigger configuration of the {@link EnableElasticsearchRepositories}
|
||||
* annotation.
|
||||
*
|
||||
* {@link org.springframework.context.annotation.ImportBeanDefinitionRegistrar} implementation to trigger configuration
|
||||
* of the {@link EnableElasticsearchRepositories} annotation.
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
|
||||
@@ -23,12 +23,11 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi
|
||||
import org.springframework.data.repository.config.XmlRepositoryConfigurationSource;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* {@link org.springframework.data.repository.config.RepositoryConfigurationExtension} implementation to configure Elasticsearch repository configuration support,
|
||||
* evaluating the {@link EnableElasticsearchRepositories} annotation or the equivalent XML element.
|
||||
*
|
||||
* {@link org.springframework.data.repository.config.RepositoryConfigurationExtension} implementation to configure
|
||||
* Elasticsearch repository configuration support, evaluating the {@link EnableElasticsearchRepositories} annotation or
|
||||
* the equivalent XML element.
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
|
||||
@@ -24,9 +24,9 @@ import org.springframework.data.repository.query.QueryLookupStrategy.Key;
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* Annotation to enable Elasticsearch repositories. Will scan the package of the annotated configuration class for Spring Data
|
||||
* repositories by default.
|
||||
*
|
||||
* Annotation to enable Elasticsearch repositories. Will scan the package of the annotated configuration class for
|
||||
* Spring Data repositories by default.
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
@@ -39,7 +39,8 @@ public @interface EnableElasticsearchRepositories {
|
||||
|
||||
/**
|
||||
* Alias for the {@link #basePackages()} attribute. Allows for more concise annotation declarations e.g.:
|
||||
* {@code @EnableElasticsearchRepositories("org.my.pkg")} instead of {@code @EnableElasticsearchRepositories(basePackages="org.my.pkg")}.
|
||||
* {@code @EnableElasticsearchRepositories("org.my.pkg")} instead of
|
||||
* {@code @EnableElasticsearchRepositories(basePackages="org.my.pkg")}.
|
||||
*/
|
||||
String[] value() default {};
|
||||
|
||||
@@ -85,16 +86,17 @@ public @interface EnableElasticsearchRepositories {
|
||||
String namedQueriesLocation() default "";
|
||||
|
||||
/**
|
||||
* Returns the key of the {@link org.springframework.data.repository.query.QueryLookupStrategy} to be used for lookup queries for query methods. Defaults to
|
||||
* Returns the key of the {@link org.springframework.data.repository.query.QueryLookupStrategy} to be used for lookup
|
||||
* queries for query methods. Defaults to
|
||||
* {@link org.springframework.data.repository.query.QueryLookupStrategy.Key#CREATE_IF_NOT_FOUND}.
|
||||
*
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
Key queryLookupStrategy() default Key.CREATE_IF_NOT_FOUND;
|
||||
|
||||
/**
|
||||
* Returns the {@link org.springframework.beans.factory.FactoryBean} class to be used for each repository instance. Defaults to
|
||||
* {@link ElasticsearchRepositoryFactoryBean}.
|
||||
* Returns the {@link org.springframework.beans.factory.FactoryBean} class to be used for each repository instance.
|
||||
* Defaults to {@link ElasticsearchRepositoryFactoryBean}.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
@@ -103,8 +105,8 @@ public @interface EnableElasticsearchRepositories {
|
||||
// Elasticsearch specific configuration
|
||||
|
||||
/**
|
||||
* Configures the name of the {@link ElasticsearchTemplate} bean definition to be used to create repositories discovered
|
||||
* through this annotation. Defaults to {@code elasticsearchTemplate}.
|
||||
* Configures the name of the {@link ElasticsearchTemplate} bean definition to be used to create repositories
|
||||
* discovered through this annotation. Defaults to {@code elasticsearchTemplate}.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
|
||||
@@ -21,24 +21,25 @@ import org.springframework.data.repository.query.RepositoryQuery;
|
||||
|
||||
/**
|
||||
* AbstractElasticsearchRepositoryQuery
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
|
||||
public abstract class AbstractElasticsearchRepositoryQuery implements RepositoryQuery {
|
||||
|
||||
protected ElasticsearchQueryMethod queryMethod;
|
||||
protected ElasticsearchOperations elasticsearchOperations;
|
||||
protected ElasticsearchQueryMethod queryMethod;
|
||||
protected ElasticsearchOperations elasticsearchOperations;
|
||||
|
||||
public AbstractElasticsearchRepositoryQuery(ElasticsearchQueryMethod queryMethod, ElasticsearchOperations elasticsearchOperations) {
|
||||
this.queryMethod = queryMethod;
|
||||
this.elasticsearchOperations = elasticsearchOperations;
|
||||
}
|
||||
public AbstractElasticsearchRepositoryQuery(ElasticsearchQueryMethod queryMethod,
|
||||
ElasticsearchOperations elasticsearchOperations) {
|
||||
this.queryMethod = queryMethod;
|
||||
this.elasticsearchOperations = elasticsearchOperations;
|
||||
}
|
||||
|
||||
@Override
|
||||
public QueryMethod getQueryMethod() {
|
||||
return queryMethod;
|
||||
}
|
||||
@Override
|
||||
public QueryMethod getQueryMethod() {
|
||||
return queryMethod;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -15,7 +15,6 @@
|
||||
*/
|
||||
package org.springframework.data.elasticsearch.repository.query;
|
||||
|
||||
|
||||
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
|
||||
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentProperty;
|
||||
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
|
||||
@@ -25,40 +24,39 @@ import org.springframework.data.repository.query.ParametersParameterAccessor;
|
||||
import org.springframework.data.repository.query.parser.PartTree;
|
||||
|
||||
/**
|
||||
* ElasticsearchPartQuery
|
||||
*
|
||||
* ElasticsearchPartQuery
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
public class ElasticsearchPartQuery extends AbstractElasticsearchRepositoryQuery{
|
||||
public class ElasticsearchPartQuery extends AbstractElasticsearchRepositoryQuery {
|
||||
|
||||
private final PartTree tree;
|
||||
private final MappingContext<?, ElasticsearchPersistentProperty> mappingContext;
|
||||
private final PartTree tree;
|
||||
private final MappingContext<?, ElasticsearchPersistentProperty> mappingContext;
|
||||
|
||||
public ElasticsearchPartQuery(ElasticsearchQueryMethod method, ElasticsearchOperations elasticsearchOperations) {
|
||||
super(method, elasticsearchOperations);
|
||||
this.tree = new PartTree(method.getName(), method.getEntityInformation().getJavaType());
|
||||
this.mappingContext = elasticsearchOperations.getElasticsearchConverter().getMappingContext();
|
||||
}
|
||||
|
||||
public ElasticsearchPartQuery(ElasticsearchQueryMethod method, ElasticsearchOperations elasticsearchOperations) {
|
||||
super(method, elasticsearchOperations);
|
||||
this.tree = new PartTree(method.getName(), method.getEntityInformation().getJavaType());
|
||||
this.mappingContext = elasticsearchOperations.getElasticsearchConverter().getMappingContext();
|
||||
}
|
||||
@Override
|
||||
public Object execute(Object[] parameters) {
|
||||
ParametersParameterAccessor accessor = new ParametersParameterAccessor(queryMethod.getParameters(), parameters);
|
||||
CriteriaQuery query = createQuery(accessor);
|
||||
if (queryMethod.isPageQuery()) {
|
||||
query.setPageable(accessor.getPageable());
|
||||
return elasticsearchOperations.queryForPage(query, queryMethod.getEntityInformation().getJavaType());
|
||||
} else if (queryMethod.isCollectionQuery()) {
|
||||
if (accessor.getPageable() != null) {
|
||||
query.setPageable(accessor.getPageable());
|
||||
}
|
||||
return elasticsearchOperations.queryForList(query, queryMethod.getEntityInformation().getJavaType());
|
||||
}
|
||||
return elasticsearchOperations.queryForObject(query, queryMethod.getEntityInformation().getJavaType());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object execute(Object[] parameters) {
|
||||
ParametersParameterAccessor accessor = new ParametersParameterAccessor(queryMethod.getParameters(), parameters);
|
||||
CriteriaQuery query = createQuery(accessor);
|
||||
if(queryMethod.isPageQuery()){
|
||||
query.setPageable(accessor.getPageable());
|
||||
return elasticsearchOperations.queryForPage(query, queryMethod.getEntityInformation().getJavaType());
|
||||
} else if (queryMethod.isCollectionQuery()) {
|
||||
if(accessor.getPageable() != null){
|
||||
query.setPageable(accessor.getPageable());
|
||||
}
|
||||
return elasticsearchOperations.queryForList(query,queryMethod.getEntityInformation().getJavaType());
|
||||
}
|
||||
return elasticsearchOperations.queryForObject(query, queryMethod.getEntityInformation().getJavaType());
|
||||
}
|
||||
|
||||
public CriteriaQuery createQuery(ParametersParameterAccessor accessor) {
|
||||
return new ElasticsearchQueryCreator(tree, accessor, mappingContext).createQuery();
|
||||
}
|
||||
public CriteriaQuery createQuery(ParametersParameterAccessor accessor) {
|
||||
return new ElasticsearchQueryCreator(tree, accessor, mappingContext).createQuery();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,33 +26,35 @@ import org.springframework.util.StringUtils;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
/**
|
||||
* ElasticsearchQueryMethod
|
||||
*
|
||||
* ElasticsearchQueryMethod
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
public class ElasticsearchQueryMethod extends QueryMethod {
|
||||
|
||||
private final ElasticsearchEntityInformation<?, ?> entityInformation;
|
||||
private Method method;
|
||||
private final ElasticsearchEntityInformation<?, ?> entityInformation;
|
||||
private Method method;
|
||||
|
||||
public ElasticsearchQueryMethod(Method method, RepositoryMetadata metadata, ElasticsearchEntityInformationCreator elasticsearchEntityInformationCreator) {
|
||||
super(method, metadata);
|
||||
this.entityInformation = elasticsearchEntityInformationCreator.getEntityInformation(metadata.getReturnedDomainClass(method));
|
||||
this.method = method;
|
||||
}
|
||||
public ElasticsearchQueryMethod(Method method, RepositoryMetadata metadata,
|
||||
ElasticsearchEntityInformationCreator elasticsearchEntityInformationCreator) {
|
||||
super(method, metadata);
|
||||
this.entityInformation = elasticsearchEntityInformationCreator.getEntityInformation(metadata
|
||||
.getReturnedDomainClass(method));
|
||||
this.method = method;
|
||||
}
|
||||
|
||||
public boolean hasAnnotatedQuery() {
|
||||
return getQueryAnnotation() != null;
|
||||
}
|
||||
public boolean hasAnnotatedQuery() {
|
||||
return getQueryAnnotation() != null;
|
||||
}
|
||||
|
||||
public String getAnnotatedQuery() {
|
||||
String query = (String) AnnotationUtils.getValue(getQueryAnnotation(), "value");
|
||||
return StringUtils.hasText(query) ? query : null;
|
||||
}
|
||||
public String getAnnotatedQuery() {
|
||||
String query = (String) AnnotationUtils.getValue(getQueryAnnotation(), "value");
|
||||
return StringUtils.hasText(query) ? query : null;
|
||||
}
|
||||
|
||||
private Query getQueryAnnotation() {
|
||||
return this.method.getAnnotation(Query.class);
|
||||
}
|
||||
private Query getQueryAnnotation() {
|
||||
return this.method.getAnnotation(Query.class);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -15,7 +15,6 @@
|
||||
*/
|
||||
package org.springframework.data.elasticsearch.repository.query;
|
||||
|
||||
|
||||
import org.springframework.core.convert.support.GenericConversionService;
|
||||
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
|
||||
import org.springframework.data.elasticsearch.core.convert.DateTimeConverters;
|
||||
@@ -28,78 +27,78 @@ import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* ElasticsearchStringQuery
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
public class ElasticsearchStringQuery extends AbstractElasticsearchRepositoryQuery{
|
||||
public class ElasticsearchStringQuery extends AbstractElasticsearchRepositoryQuery {
|
||||
|
||||
private static final Pattern PARAMETER_PLACEHOLDER = Pattern.compile("\\?(\\d+)");
|
||||
private String query;
|
||||
private static final Pattern PARAMETER_PLACEHOLDER = Pattern.compile("\\?(\\d+)");
|
||||
private String query;
|
||||
|
||||
private final GenericConversionService conversionService = new GenericConversionService();
|
||||
private final GenericConversionService conversionService = new GenericConversionService();
|
||||
|
||||
{
|
||||
if (!conversionService.canConvert(java.util.Date.class, String.class)) {
|
||||
conversionService.addConverter(DateTimeConverters.JavaDateConverter.INSTANCE);
|
||||
}
|
||||
if (!conversionService.canConvert(org.joda.time.ReadableInstant.class, String.class)) {
|
||||
conversionService.addConverter(DateTimeConverters.JodaDateTimeConverter.INSTANCE);
|
||||
}
|
||||
if (!conversionService.canConvert(org.joda.time.LocalDateTime.class, String.class)) {
|
||||
conversionService.addConverter(DateTimeConverters.JodaLocalDateTimeConverter.INSTANCE);
|
||||
}
|
||||
{
|
||||
if (!conversionService.canConvert(java.util.Date.class, String.class)) {
|
||||
conversionService.addConverter(DateTimeConverters.JavaDateConverter.INSTANCE);
|
||||
}
|
||||
if (!conversionService.canConvert(org.joda.time.ReadableInstant.class, String.class)) {
|
||||
conversionService.addConverter(DateTimeConverters.JodaDateTimeConverter.INSTANCE);
|
||||
}
|
||||
if (!conversionService.canConvert(org.joda.time.LocalDateTime.class, String.class)) {
|
||||
conversionService.addConverter(DateTimeConverters.JodaLocalDateTimeConverter.INSTANCE);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public ElasticsearchStringQuery(ElasticsearchQueryMethod queryMethod, ElasticsearchOperations elasticsearchOperations, String query) {
|
||||
super(queryMethod, elasticsearchOperations);
|
||||
Assert.notNull(query, "Query cannot be empty");
|
||||
this.query = query;
|
||||
}
|
||||
public ElasticsearchStringQuery(ElasticsearchQueryMethod queryMethod,
|
||||
ElasticsearchOperations elasticsearchOperations, String query) {
|
||||
super(queryMethod, elasticsearchOperations);
|
||||
Assert.notNull(query, "Query cannot be empty");
|
||||
this.query = query;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object execute(Object[] parameters) {
|
||||
ParametersParameterAccessor accessor = new ParametersParameterAccessor(queryMethod.getParameters(), parameters);
|
||||
StringQuery stringQuery = createQuery(accessor);
|
||||
if(queryMethod.isPageQuery()){
|
||||
stringQuery.setPageable(accessor.getPageable());
|
||||
return elasticsearchOperations.queryForPage(stringQuery, queryMethod.getEntityInformation().getJavaType());
|
||||
} else if(queryMethod.isCollectionQuery()) {
|
||||
if(accessor.getPageable() != null) {
|
||||
stringQuery.setPageable(accessor.getPageable());
|
||||
}
|
||||
return elasticsearchOperations.queryForList(stringQuery,queryMethod.getEntityInformation().getJavaType());
|
||||
}
|
||||
@Override
|
||||
public Object execute(Object[] parameters) {
|
||||
ParametersParameterAccessor accessor = new ParametersParameterAccessor(queryMethod.getParameters(), parameters);
|
||||
StringQuery stringQuery = createQuery(accessor);
|
||||
if (queryMethod.isPageQuery()) {
|
||||
stringQuery.setPageable(accessor.getPageable());
|
||||
return elasticsearchOperations.queryForPage(stringQuery, queryMethod.getEntityInformation().getJavaType());
|
||||
} else if (queryMethod.isCollectionQuery()) {
|
||||
if (accessor.getPageable() != null) {
|
||||
stringQuery.setPageable(accessor.getPageable());
|
||||
}
|
||||
return elasticsearchOperations.queryForList(stringQuery, queryMethod.getEntityInformation().getJavaType());
|
||||
}
|
||||
|
||||
return elasticsearchOperations.queryForObject(stringQuery, queryMethod.getEntityInformation().getJavaType());
|
||||
}
|
||||
return elasticsearchOperations.queryForObject(stringQuery, queryMethod.getEntityInformation().getJavaType());
|
||||
}
|
||||
|
||||
protected StringQuery createQuery(ParametersParameterAccessor parameterAccessor) {
|
||||
String queryString = replacePlaceholders(this.query, parameterAccessor);
|
||||
return new StringQuery(queryString);
|
||||
}
|
||||
|
||||
protected StringQuery createQuery(ParametersParameterAccessor parameterAccessor) {
|
||||
String queryString = replacePlaceholders(this.query, parameterAccessor);
|
||||
return new StringQuery(queryString);
|
||||
}
|
||||
private String replacePlaceholders(String input, ParametersParameterAccessor accessor) {
|
||||
Matcher matcher = PARAMETER_PLACEHOLDER.matcher(input);
|
||||
String result = input;
|
||||
while (matcher.find()) {
|
||||
String group = matcher.group();
|
||||
int index = Integer.parseInt(matcher.group(1));
|
||||
result = result.replace(group, getParameterWithIndex(accessor, index));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private String replacePlaceholders(String input, ParametersParameterAccessor accessor) {
|
||||
Matcher matcher = PARAMETER_PLACEHOLDER.matcher(input);
|
||||
String result = input;
|
||||
while (matcher.find()) {
|
||||
String group = matcher.group();
|
||||
int index = Integer.parseInt(matcher.group(1));
|
||||
result = result.replace(group, getParameterWithIndex(accessor, index));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private String getParameterWithIndex(ParametersParameterAccessor accessor, int index) {
|
||||
Object parameter = accessor.getBindableValue(index);
|
||||
if (parameter == null) {
|
||||
return "null";
|
||||
}
|
||||
if (conversionService.canConvert(parameter.getClass(), String.class)) {
|
||||
return conversionService.convert(parameter, String.class);
|
||||
}
|
||||
return parameter.toString();
|
||||
}
|
||||
private String getParameterWithIndex(ParametersParameterAccessor accessor, int index) {
|
||||
Object parameter = accessor.getBindableValue(index);
|
||||
if (parameter == null) {
|
||||
return "null";
|
||||
}
|
||||
if (conversionService.canConvert(parameter.getClass(), String.class)) {
|
||||
return conversionService.convert(parameter, String.class);
|
||||
}
|
||||
return parameter.toString();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,6 @@
|
||||
*/
|
||||
package org.springframework.data.elasticsearch.repository.query.parser;
|
||||
|
||||
|
||||
import org.springframework.dao.InvalidDataAccessApiUsageException;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentProperty;
|
||||
@@ -33,104 +32,106 @@ import java.util.Iterator;
|
||||
|
||||
/**
|
||||
* ElasticsearchQueryCreator
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
public class ElasticsearchQueryCreator extends AbstractQueryCreator<CriteriaQuery,CriteriaQuery>{
|
||||
public class ElasticsearchQueryCreator extends AbstractQueryCreator<CriteriaQuery, CriteriaQuery> {
|
||||
|
||||
private final MappingContext<?, ElasticsearchPersistentProperty> context;
|
||||
private final MappingContext<?, ElasticsearchPersistentProperty> context;
|
||||
|
||||
public ElasticsearchQueryCreator(PartTree tree, ParameterAccessor parameters, MappingContext<?, ElasticsearchPersistentProperty> context) {
|
||||
super(tree, parameters);
|
||||
this.context = context;
|
||||
}
|
||||
public ElasticsearchQueryCreator(PartTree tree, ParameterAccessor parameters,
|
||||
MappingContext<?, ElasticsearchPersistentProperty> context) {
|
||||
super(tree, parameters);
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
public ElasticsearchQueryCreator(PartTree tree, MappingContext<?, ElasticsearchPersistentProperty> context) {
|
||||
super(tree);
|
||||
this.context = context;
|
||||
}
|
||||
public ElasticsearchQueryCreator(PartTree tree, MappingContext<?, ElasticsearchPersistentProperty> context) {
|
||||
super(tree);
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected CriteriaQuery create(Part part, Iterator<Object> iterator) {
|
||||
PersistentPropertyPath<ElasticsearchPersistentProperty> path = context.getPersistentPropertyPath(part.getProperty());
|
||||
return new CriteriaQuery(from(part.getType(),
|
||||
new Criteria(path.toDotPath(ElasticsearchPersistentProperty.PropertyToFieldNameConverter.INSTANCE)), iterator));
|
||||
}
|
||||
@Override
|
||||
protected CriteriaQuery create(Part part, Iterator<Object> iterator) {
|
||||
PersistentPropertyPath<ElasticsearchPersistentProperty> path = context
|
||||
.getPersistentPropertyPath(part.getProperty());
|
||||
return new CriteriaQuery(from(part.getType(),
|
||||
new Criteria(path.toDotPath(ElasticsearchPersistentProperty.PropertyToFieldNameConverter.INSTANCE)), iterator));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected CriteriaQuery and(Part part, CriteriaQuery base, Iterator<Object> iterator) {
|
||||
if (base == null) {
|
||||
return create(part, iterator);
|
||||
}
|
||||
PersistentPropertyPath<ElasticsearchPersistentProperty> path = context.getPersistentPropertyPath(part.getProperty());
|
||||
return base.addCriteria(from(part.getType(),
|
||||
new Criteria(path.toDotPath(ElasticsearchPersistentProperty.PropertyToFieldNameConverter.INSTANCE)), iterator));
|
||||
}
|
||||
@Override
|
||||
protected CriteriaQuery and(Part part, CriteriaQuery base, Iterator<Object> iterator) {
|
||||
if (base == null) {
|
||||
return create(part, iterator);
|
||||
}
|
||||
PersistentPropertyPath<ElasticsearchPersistentProperty> path = context
|
||||
.getPersistentPropertyPath(part.getProperty());
|
||||
return base.addCriteria(from(part.getType(),
|
||||
new Criteria(path.toDotPath(ElasticsearchPersistentProperty.PropertyToFieldNameConverter.INSTANCE)), iterator));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected CriteriaQuery or(CriteriaQuery base, CriteriaQuery query) {
|
||||
return new CriteriaQuery(base.getCriteria().or(query.getCriteria()));
|
||||
}
|
||||
@Override
|
||||
protected CriteriaQuery or(CriteriaQuery base, CriteriaQuery query) {
|
||||
return new CriteriaQuery(base.getCriteria().or(query.getCriteria()));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected CriteriaQuery complete(CriteriaQuery query, Sort sort) {
|
||||
if (query == null) {
|
||||
return null;
|
||||
}
|
||||
return query.addSort(sort);
|
||||
}
|
||||
@Override
|
||||
protected CriteriaQuery complete(CriteriaQuery query, Sort sort) {
|
||||
if (query == null) {
|
||||
return null;
|
||||
}
|
||||
return query.addSort(sort);
|
||||
}
|
||||
|
||||
private Criteria from(Part.Type type, Criteria instance, Iterator<?> parameters) {
|
||||
Criteria criteria = instance;
|
||||
if (criteria == null) {
|
||||
criteria = new Criteria();
|
||||
}
|
||||
switch (type) {
|
||||
case TRUE:
|
||||
return criteria.is(true);
|
||||
case FALSE:
|
||||
return criteria.is(false);
|
||||
case SIMPLE_PROPERTY:
|
||||
return criteria.is(parameters.next());
|
||||
case NEGATING_SIMPLE_PROPERTY:
|
||||
return criteria.is(parameters.next()).not();
|
||||
case REGEX:
|
||||
return criteria.expression(parameters.next().toString());
|
||||
case LIKE:
|
||||
case STARTING_WITH:
|
||||
return criteria.startsWith(parameters.next().toString());
|
||||
case ENDING_WITH:
|
||||
return criteria.endsWith(parameters.next().toString());
|
||||
case CONTAINING:
|
||||
return criteria.contains(parameters.next().toString());
|
||||
case AFTER:
|
||||
case GREATER_THAN:
|
||||
case GREATER_THAN_EQUAL:
|
||||
return criteria.greaterThanEqual(parameters.next());
|
||||
case BEFORE:
|
||||
case LESS_THAN:
|
||||
case LESS_THAN_EQUAL:
|
||||
return criteria.lessThanEqual(parameters.next());
|
||||
case BETWEEN:
|
||||
return criteria.between(parameters.next(), parameters.next());
|
||||
case IN:
|
||||
return criteria.in(asArray(parameters.next()));
|
||||
case NOT_IN:
|
||||
return criteria.in(asArray(parameters.next())).not();
|
||||
default:
|
||||
throw new InvalidDataAccessApiUsageException("Illegal criteria found '" + type + "'.");
|
||||
}
|
||||
}
|
||||
|
||||
private Criteria from(Part.Type type, Criteria instance, Iterator<?> parameters) {
|
||||
Criteria criteria = instance;
|
||||
if (criteria == null) {
|
||||
criteria = new Criteria();
|
||||
}
|
||||
switch (type) {
|
||||
case TRUE:
|
||||
return criteria.is(true);
|
||||
case FALSE:
|
||||
return criteria.is(false);
|
||||
case SIMPLE_PROPERTY:
|
||||
return criteria.is(parameters.next());
|
||||
case NEGATING_SIMPLE_PROPERTY:
|
||||
return criteria.is(parameters.next()).not();
|
||||
case REGEX:
|
||||
return criteria.expression(parameters.next().toString());
|
||||
case LIKE:
|
||||
case STARTING_WITH:
|
||||
return criteria.startsWith(parameters.next().toString());
|
||||
case ENDING_WITH:
|
||||
return criteria.endsWith(parameters.next().toString());
|
||||
case CONTAINING:
|
||||
return criteria.contains(parameters.next().toString());
|
||||
case AFTER:
|
||||
case GREATER_THAN:
|
||||
case GREATER_THAN_EQUAL:
|
||||
return criteria.greaterThanEqual(parameters.next());
|
||||
case BEFORE:
|
||||
case LESS_THAN:
|
||||
case LESS_THAN_EQUAL:
|
||||
return criteria.lessThanEqual(parameters.next());
|
||||
case BETWEEN:
|
||||
return criteria.between(parameters.next(), parameters.next());
|
||||
case IN:
|
||||
return criteria.in(asArray(parameters.next()));
|
||||
case NOT_IN:
|
||||
return criteria.in(asArray(parameters.next())).not();
|
||||
default:
|
||||
throw new InvalidDataAccessApiUsageException("Illegal criteria found '" + type + "'.");
|
||||
}
|
||||
}
|
||||
|
||||
private Object[] asArray(Object o) {
|
||||
if (o instanceof Collection) {
|
||||
return ((Collection<?>) o).toArray();
|
||||
} else if (o.getClass().isArray()) {
|
||||
return (Object[]) o;
|
||||
}
|
||||
return new Object[] { o };
|
||||
}
|
||||
private Object[] asArray(Object o) {
|
||||
if (o instanceof Collection) {
|
||||
return ((Collection<?>) o).toArray();
|
||||
} else if (o.getClass().isArray()) {
|
||||
return (Object[]) o;
|
||||
}
|
||||
return new Object[] { o };
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -36,283 +36,273 @@ import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
|
||||
import static org.springframework.data.elasticsearch.core.query.Query.DEFAULT_PAGE;
|
||||
|
||||
/**
|
||||
* Elasticsearch specific repository implementation. Likely to be used as target within {@link ElasticsearchRepositoryFactory}
|
||||
*
|
||||
*
|
||||
* Elasticsearch specific repository implementation. Likely to be used as target within
|
||||
* {@link ElasticsearchRepositoryFactory}
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
* @author Ryan Henszey
|
||||
*/
|
||||
public abstract class AbstractElasticsearchRepository<T,ID extends Serializable> implements ElasticsearchRepository<T, ID> {
|
||||
public abstract class AbstractElasticsearchRepository<T, ID extends Serializable> implements
|
||||
ElasticsearchRepository<T, ID> {
|
||||
|
||||
protected ElasticsearchOperations elasticsearchOperations;
|
||||
protected Class<T> entityClass;
|
||||
protected ElasticsearchEntityInformation<T, ID> entityInformation;
|
||||
|
||||
protected ElasticsearchOperations elasticsearchOperations;
|
||||
protected Class<T> entityClass;
|
||||
protected ElasticsearchEntityInformation<T, ID> entityInformation;
|
||||
public AbstractElasticsearchRepository() {
|
||||
}
|
||||
|
||||
public AbstractElasticsearchRepository() {
|
||||
}
|
||||
public AbstractElasticsearchRepository(ElasticsearchOperations elasticsearchOperations) {
|
||||
Assert.notNull(elasticsearchOperations);
|
||||
this.setElasticsearchOperations(elasticsearchOperations);
|
||||
}
|
||||
|
||||
public AbstractElasticsearchRepository(ElasticsearchOperations elasticsearchOperations) {
|
||||
Assert.notNull(elasticsearchOperations);
|
||||
this.setElasticsearchOperations(elasticsearchOperations);
|
||||
}
|
||||
public AbstractElasticsearchRepository(ElasticsearchEntityInformation<T, ID> metadata,
|
||||
ElasticsearchOperations elasticsearchOperations) {
|
||||
this(elasticsearchOperations);
|
||||
Assert.notNull(metadata);
|
||||
this.entityInformation = metadata;
|
||||
setEntityClass(this.entityInformation.getJavaType());
|
||||
createIndex();
|
||||
putMapping();
|
||||
}
|
||||
|
||||
public AbstractElasticsearchRepository(ElasticsearchEntityInformation<T, ID> metadata, ElasticsearchOperations elasticsearchOperations) {
|
||||
this(elasticsearchOperations);
|
||||
Assert.notNull(metadata);
|
||||
this.entityInformation = metadata;
|
||||
setEntityClass(this.entityInformation.getJavaType());
|
||||
createIndex();
|
||||
putMapping();
|
||||
}
|
||||
private void createIndex() {
|
||||
elasticsearchOperations.createIndex(getEntityClass());
|
||||
}
|
||||
|
||||
private void createIndex(){
|
||||
elasticsearchOperations.createIndex(getEntityClass());
|
||||
}
|
||||
private void putMapping() {
|
||||
elasticsearchOperations.putMapping(getEntityClass());
|
||||
}
|
||||
|
||||
private void putMapping(){
|
||||
elasticsearchOperations.putMapping(getEntityClass());
|
||||
}
|
||||
@Override
|
||||
public T findOne(ID id) {
|
||||
GetQuery query = new GetQuery();
|
||||
query.setId(stringIdRepresentation(id));
|
||||
return elasticsearchOperations.queryForObject(query, getEntityClass());
|
||||
}
|
||||
|
||||
@Override
|
||||
public T findOne(ID id) {
|
||||
GetQuery query = new GetQuery();
|
||||
query.setId(stringIdRepresentation(id));
|
||||
return elasticsearchOperations.queryForObject(query, getEntityClass());
|
||||
}
|
||||
@Override
|
||||
public Iterable<T> findAll() {
|
||||
int itemCount = (int) this.count();
|
||||
if (itemCount == 0) {
|
||||
return new PageImpl<T>(Collections.<T> emptyList());
|
||||
}
|
||||
return this.findAll(new PageRequest(0, Math.max(1, itemCount)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterable<T> findAll() {
|
||||
int itemCount = (int) this.count();
|
||||
if (itemCount == 0) {
|
||||
return new PageImpl<T>(Collections.<T> emptyList());
|
||||
}
|
||||
return this.findAll(new PageRequest(0, Math.max(1, itemCount)));
|
||||
}
|
||||
@Override
|
||||
public Page<T> findAll(Pageable pageable) {
|
||||
SearchQuery query = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).withPageable(pageable).build();
|
||||
return elasticsearchOperations.queryForPage(query, getEntityClass());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Page<T> findAll(Pageable pageable) {
|
||||
SearchQuery query = new NativeSearchQueryBuilder()
|
||||
.withQuery(matchAllQuery())
|
||||
.withPageable(pageable)
|
||||
.build();
|
||||
return elasticsearchOperations.queryForPage(query, getEntityClass());
|
||||
}
|
||||
@Override
|
||||
public Iterable<T> findAll(Sort sort) {
|
||||
int itemCount = (int) this.count();
|
||||
if (itemCount == 0) {
|
||||
return new PageImpl<T>(Collections.<T> emptyList());
|
||||
}
|
||||
SearchQuery query = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
|
||||
.withPageable(new PageRequest(0, itemCount, sort)).build();
|
||||
return elasticsearchOperations.queryForPage(query, getEntityClass());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterable<T> findAll(Sort sort) {
|
||||
int itemCount = (int) this.count();
|
||||
if (itemCount == 0) {
|
||||
return new PageImpl<T>(Collections.<T> emptyList());
|
||||
}
|
||||
SearchQuery query = new NativeSearchQueryBuilder()
|
||||
.withQuery(matchAllQuery())
|
||||
.withPageable(new PageRequest(0,itemCount, sort))
|
||||
.build();
|
||||
return elasticsearchOperations.queryForPage(query, getEntityClass());
|
||||
}
|
||||
@Override
|
||||
public Iterable<T> findAll(Iterable<ID> ids) {
|
||||
SearchQuery query = new NativeSearchQueryBuilder().withQuery(inQuery(entityInformation.getIdAttribute(), ids))
|
||||
.build();
|
||||
return elasticsearchOperations.queryForPage(query, getEntityClass());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterable<T> findAll(Iterable<ID> ids) {
|
||||
SearchQuery query = new NativeSearchQueryBuilder()
|
||||
.withQuery(inQuery(entityInformation.getIdAttribute(), ids))
|
||||
.build();
|
||||
return elasticsearchOperations.queryForPage(query, getEntityClass());
|
||||
}
|
||||
@Override
|
||||
public long count() {
|
||||
SearchQuery query = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build();
|
||||
return elasticsearchOperations.count(query, getEntityClass());
|
||||
}
|
||||
|
||||
@Override
|
||||
public long count() {
|
||||
SearchQuery query = new NativeSearchQueryBuilder()
|
||||
.withQuery(matchAllQuery()).build();
|
||||
return elasticsearchOperations.count(query,getEntityClass());
|
||||
}
|
||||
@Override
|
||||
public <S extends T> S save(S entity) {
|
||||
Assert.notNull(entity, "Cannot save 'null' entity.");
|
||||
elasticsearchOperations.index(createIndexQuery(entity));
|
||||
elasticsearchOperations.refresh(entityInformation.getIndexName(), true);
|
||||
return entity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <S extends T> S save(S entity) {
|
||||
Assert.notNull(entity, "Cannot save 'null' entity.");
|
||||
elasticsearchOperations.index(createIndexQuery(entity));
|
||||
elasticsearchOperations.refresh(entityInformation.getIndexName(), true);
|
||||
return entity;
|
||||
}
|
||||
public <S extends T> List<S> save(List<S> entities) {
|
||||
Assert.notNull(entities, "Cannot insert 'null' as a List.");
|
||||
Assert.notEmpty(entities, "Cannot insert empty List.");
|
||||
List<IndexQuery> queries = new ArrayList<IndexQuery>();
|
||||
for (S s : entities) {
|
||||
queries.add(createIndexQuery(s));
|
||||
}
|
||||
elasticsearchOperations.bulkIndex(queries);
|
||||
elasticsearchOperations.refresh(entityInformation.getIndexName(), true);
|
||||
return entities;
|
||||
}
|
||||
|
||||
public <S extends T> List<S> save(List<S> entities) {
|
||||
Assert.notNull(entities, "Cannot insert 'null' as a List.");
|
||||
Assert.notEmpty(entities,"Cannot insert empty List.");
|
||||
List<IndexQuery> queries = new ArrayList<IndexQuery>();
|
||||
for(S s:entities){
|
||||
queries.add(createIndexQuery(s));
|
||||
}
|
||||
elasticsearchOperations.bulkIndex(queries);
|
||||
elasticsearchOperations.refresh(entityInformation.getIndexName(), true);
|
||||
return entities;
|
||||
}
|
||||
@Override
|
||||
public <S extends T> S index(S entity) {
|
||||
return save(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <S extends T> S index(S entity) {
|
||||
return save(entity);
|
||||
}
|
||||
@Override
|
||||
public <S extends T> Iterable<S> save(Iterable<S> entities) {
|
||||
Assert.notNull(entities, "Cannot insert 'null' as a List.");
|
||||
if (!(entities instanceof Collection<?>)) {
|
||||
throw new InvalidDataAccessApiUsageException("Entities have to be inside a collection");
|
||||
}
|
||||
List<IndexQuery> queries = new ArrayList<IndexQuery>();
|
||||
for (S s : entities) {
|
||||
queries.add(createIndexQuery(s));
|
||||
}
|
||||
elasticsearchOperations.bulkIndex(queries);
|
||||
elasticsearchOperations.refresh(entityInformation.getIndexName(), true);
|
||||
return entities;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <S extends T> Iterable<S> save(Iterable<S> entities) {
|
||||
Assert.notNull(entities, "Cannot insert 'null' as a List.");
|
||||
if (!(entities instanceof Collection<?>)) {
|
||||
throw new InvalidDataAccessApiUsageException("Entities have to be inside a collection");
|
||||
}
|
||||
List<IndexQuery> queries = new ArrayList<IndexQuery>();
|
||||
for(S s: entities){
|
||||
queries.add(createIndexQuery(s));
|
||||
}
|
||||
elasticsearchOperations.bulkIndex(queries);
|
||||
elasticsearchOperations.refresh(entityInformation.getIndexName(), true);
|
||||
return entities;
|
||||
}
|
||||
@Override
|
||||
public boolean exists(ID id) {
|
||||
return findOne(id) != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean exists(ID id) {
|
||||
return findOne(id) != null;
|
||||
}
|
||||
@Override
|
||||
public Iterable<T> search(QueryBuilder query) {
|
||||
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(query).build();
|
||||
int count = (int) elasticsearchOperations.count(searchQuery, getEntityClass());
|
||||
if (count == 0) {
|
||||
return new PageImpl<T>(Collections.<T> emptyList());
|
||||
}
|
||||
searchQuery.setPageable(new PageRequest(0, count));
|
||||
return elasticsearchOperations.queryForPage(searchQuery, getEntityClass());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterable<T> search(QueryBuilder query) {
|
||||
SearchQuery searchQuery = new NativeSearchQueryBuilder()
|
||||
.withQuery(query).build();
|
||||
int count = (int) elasticsearchOperations.count(searchQuery, getEntityClass());
|
||||
if(count == 0){
|
||||
return new PageImpl<T>(Collections.<T>emptyList());
|
||||
}
|
||||
searchQuery.setPageable(new PageRequest(0, count));
|
||||
return elasticsearchOperations.queryForPage(searchQuery, getEntityClass());
|
||||
}
|
||||
@Override
|
||||
public Page<T> search(QueryBuilder query, Pageable pageable) {
|
||||
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(query).withPageable(pageable).build();
|
||||
return elasticsearchOperations.queryForPage(searchQuery, getEntityClass());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Page<T> search(QueryBuilder query, Pageable pageable) {
|
||||
SearchQuery searchQuery = new NativeSearchQueryBuilder()
|
||||
.withQuery(query)
|
||||
.withPageable(pageable)
|
||||
.build();
|
||||
return elasticsearchOperations.queryForPage(searchQuery, getEntityClass());
|
||||
}
|
||||
@Override
|
||||
public Page<T> search(SearchQuery query) {
|
||||
return elasticsearchOperations.queryForPage(query, getEntityClass());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Page<T> search(SearchQuery query){
|
||||
return elasticsearchOperations.queryForPage(query, getEntityClass());
|
||||
}
|
||||
@Override
|
||||
public Page<T> searchSimilar(T entity, SearchQuery searchQuery) {
|
||||
Assert.notNull(entity, "Cannot search similar records for 'null'.");
|
||||
Assert.notNull(searchQuery.getFields(), "Fields cannot be 'null'");
|
||||
MoreLikeThisQuery query = new MoreLikeThisQuery();
|
||||
query.setId(stringIdRepresentation(extractIdFromBean(entity)));
|
||||
query.setPageable(searchQuery.getPageable() != null ? searchQuery.getPageable() : DEFAULT_PAGE);
|
||||
query.addFields(searchQuery.getFields().toArray(new String[searchQuery.getFields().size()]));
|
||||
if (!searchQuery.getIndices().isEmpty()) {
|
||||
query.addSearchIndices(searchQuery.getIndices().toArray(new String[searchQuery.getIndices().size()]));
|
||||
}
|
||||
if (!searchQuery.getTypes().isEmpty()) {
|
||||
query.addSearchTypes(searchQuery.getTypes().toArray(new String[searchQuery.getTypes().size()]));
|
||||
}
|
||||
return elasticsearchOperations.moreLikeThis(query, getEntityClass());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Page<T> searchSimilar(T entity, SearchQuery searchQuery) {
|
||||
Assert.notNull(entity, "Cannot search similar records for 'null'.");
|
||||
Assert.notNull(searchQuery.getFields(), "Fields cannot be 'null'");
|
||||
MoreLikeThisQuery query = new MoreLikeThisQuery();
|
||||
query.setId(stringIdRepresentation(extractIdFromBean(entity)));
|
||||
query.setPageable(searchQuery.getPageable() != null ? searchQuery.getPageable() : DEFAULT_PAGE);
|
||||
query.addFields(searchQuery.getFields().toArray(new String[searchQuery.getFields().size()]));
|
||||
if(!searchQuery.getIndices().isEmpty()) {
|
||||
query.addSearchIndices(searchQuery.getIndices().toArray(new String[searchQuery.getIndices().size()]));
|
||||
}
|
||||
if(!searchQuery.getTypes().isEmpty()){
|
||||
query.addSearchTypes(searchQuery.getTypes().toArray(new String[searchQuery.getTypes().size()]));
|
||||
}
|
||||
return elasticsearchOperations.moreLikeThis(query, getEntityClass());
|
||||
}
|
||||
@Override
|
||||
public void delete(ID id) {
|
||||
Assert.notNull(id, "Cannot delete entity with id 'null'.");
|
||||
elasticsearchOperations.delete(entityInformation.getIndexName(), entityInformation.getType(),
|
||||
stringIdRepresentation(id));
|
||||
elasticsearchOperations.refresh(entityInformation.getIndexName(), true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(T entity) {
|
||||
Assert.notNull(entity, "Cannot delete 'null' entity.");
|
||||
delete(extractIdFromBean(entity));
|
||||
elasticsearchOperations.refresh(entityInformation.getIndexName(), true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(ID id) {
|
||||
Assert.notNull(id, "Cannot delete entity with id 'null'.");
|
||||
elasticsearchOperations.delete(entityInformation.getIndexName(), entityInformation.getType(),stringIdRepresentation(id));
|
||||
elasticsearchOperations.refresh(entityInformation.getIndexName(),true);
|
||||
}
|
||||
@Override
|
||||
public void delete(Iterable<? extends T> entities) {
|
||||
Assert.notNull(entities, "Cannot delete 'null' list.");
|
||||
for (T entity : entities) {
|
||||
delete(entity);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(T entity) {
|
||||
Assert.notNull(entity, "Cannot delete 'null' entity.");
|
||||
delete(extractIdFromBean(entity));
|
||||
elasticsearchOperations.refresh(entityInformation.getIndexName(), true);
|
||||
}
|
||||
@Override
|
||||
public void deleteAll() {
|
||||
DeleteQuery deleteQuery = new DeleteQuery();
|
||||
deleteQuery.setQuery(matchAllQuery());
|
||||
elasticsearchOperations.delete(deleteQuery, getEntityClass());
|
||||
elasticsearchOperations.refresh(entityInformation.getIndexName(), true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(Iterable<? extends T> entities) {
|
||||
Assert.notNull(entities, "Cannot delete 'null' list.");
|
||||
for (T entity : entities) {
|
||||
delete(entity);
|
||||
}
|
||||
}
|
||||
private IndexQuery createIndexQuery(T entity) {
|
||||
IndexQuery query = new IndexQuery();
|
||||
query.setObject(entity);
|
||||
query.setId(stringIdRepresentation(extractIdFromBean(entity)));
|
||||
query.setVersion(extractVersionFromBean(entity));
|
||||
return query;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteAll() {
|
||||
DeleteQuery deleteQuery = new DeleteQuery();
|
||||
deleteQuery.setQuery(matchAllQuery());
|
||||
elasticsearchOperations.delete(deleteQuery, getEntityClass());
|
||||
elasticsearchOperations.refresh(entityInformation.getIndexName(),true);
|
||||
}
|
||||
@SuppressWarnings("unchecked")
|
||||
private Class<T> resolveReturnedClassFromGenericType() {
|
||||
ParameterizedType parameterizedType = resolveReturnedClassFromGenericType(getClass());
|
||||
return (Class<T>) parameterizedType.getActualTypeArguments()[0];
|
||||
}
|
||||
|
||||
private IndexQuery createIndexQuery(T entity){
|
||||
IndexQuery query = new IndexQuery();
|
||||
query.setObject(entity);
|
||||
query.setId(stringIdRepresentation(extractIdFromBean(entity)));
|
||||
query.setVersion(extractVersionFromBean(entity));
|
||||
return query;
|
||||
}
|
||||
private ParameterizedType resolveReturnedClassFromGenericType(Class<?> clazz) {
|
||||
Object genericSuperclass = clazz.getGenericSuperclass();
|
||||
if (genericSuperclass instanceof ParameterizedType) {
|
||||
ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
|
||||
Type rawtype = parameterizedType.getRawType();
|
||||
if (SimpleElasticsearchRepository.class.equals(rawtype)) {
|
||||
return parameterizedType;
|
||||
}
|
||||
}
|
||||
return resolveReturnedClassFromGenericType(clazz.getSuperclass());
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Class<T> resolveReturnedClassFromGenericType() {
|
||||
ParameterizedType parameterizedType = resolveReturnedClassFromGenericType(getClass());
|
||||
return (Class<T>) parameterizedType.getActualTypeArguments()[0];
|
||||
}
|
||||
public Class<T> getEntityClass() {
|
||||
if (!isEntityClassSet()) {
|
||||
try {
|
||||
this.entityClass = resolveReturnedClassFromGenericType();
|
||||
} catch (Exception e) {
|
||||
throw new InvalidDataAccessApiUsageException("Unable to resolve EntityClass. Please use according setter!", e);
|
||||
}
|
||||
}
|
||||
return entityClass;
|
||||
}
|
||||
|
||||
private ParameterizedType resolveReturnedClassFromGenericType(Class<?> clazz) {
|
||||
Object genericSuperclass = clazz.getGenericSuperclass();
|
||||
if (genericSuperclass instanceof ParameterizedType) {
|
||||
ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
|
||||
Type rawtype = parameterizedType.getRawType();
|
||||
if (SimpleElasticsearchRepository.class.equals(rawtype)) {
|
||||
return parameterizedType;
|
||||
}
|
||||
}
|
||||
return resolveReturnedClassFromGenericType(clazz.getSuperclass());
|
||||
}
|
||||
private boolean isEntityClassSet() {
|
||||
return entityClass != null;
|
||||
}
|
||||
|
||||
public Class<T> getEntityClass() {
|
||||
if (!isEntityClassSet()) {
|
||||
try {
|
||||
this.entityClass = resolveReturnedClassFromGenericType();
|
||||
} catch (Exception e) {
|
||||
throw new InvalidDataAccessApiUsageException("Unable to resolve EntityClass. Please use according setter!", e);
|
||||
}
|
||||
}
|
||||
return entityClass;
|
||||
}
|
||||
public final void setEntityClass(Class<T> entityClass) {
|
||||
Assert.notNull(entityClass, "EntityClass must not be null.");
|
||||
this.entityClass = entityClass;
|
||||
}
|
||||
|
||||
private boolean isEntityClassSet() {
|
||||
return entityClass != null;
|
||||
}
|
||||
public final void setElasticsearchOperations(ElasticsearchOperations elasticsearchOperations) {
|
||||
Assert.notNull(elasticsearchOperations, "ElasticsearchOperations must not be null.");
|
||||
this.elasticsearchOperations = elasticsearchOperations;
|
||||
}
|
||||
|
||||
public final void setEntityClass(Class<T> entityClass) {
|
||||
Assert.notNull(entityClass, "EntityClass must not be null.");
|
||||
this.entityClass = entityClass;
|
||||
}
|
||||
protected ID extractIdFromBean(T entity) {
|
||||
if (entityInformation != null) {
|
||||
return entityInformation.getId(entity);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public final void setElasticsearchOperations(ElasticsearchOperations elasticsearchOperations) {
|
||||
Assert.notNull(elasticsearchOperations, "ElasticsearchOperations must not be null.");
|
||||
this.elasticsearchOperations = elasticsearchOperations;
|
||||
}
|
||||
protected abstract String stringIdRepresentation(ID id);
|
||||
|
||||
|
||||
protected ID extractIdFromBean(T entity) {
|
||||
if (entityInformation != null) {
|
||||
return entityInformation.getId(entity);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
protected abstract String stringIdRepresentation(ID id);
|
||||
|
||||
private Long extractVersionFromBean(T entity){
|
||||
if (entityInformation != null) {
|
||||
return entityInformation.getVersion(entity);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
private Long extractVersionFromBean(T entity) {
|
||||
if (entityInformation != null) {
|
||||
return entityInformation.getVersion(entity);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -22,14 +22,17 @@ import java.io.Serializable;
|
||||
/**
|
||||
* @param <T>
|
||||
* @param <ID>
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
public interface ElasticsearchEntityInformation<T, ID extends Serializable> extends EntityInformation<T, ID> {
|
||||
|
||||
String getIdAttribute();
|
||||
String getIndexName();
|
||||
String getType();
|
||||
Long getVersion(T entity);
|
||||
|
||||
String getIndexName();
|
||||
|
||||
String getType();
|
||||
|
||||
Long getVersion(T entity);
|
||||
}
|
||||
|
||||
@@ -18,8 +18,8 @@ package org.springframework.data.elasticsearch.repository.support;
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* ElasticsearchEntityInformationCreator
|
||||
*
|
||||
* ElasticsearchEntityInformationCreator
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
|
||||
@@ -24,7 +24,7 @@ import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* ElasticsearchEntityInformationCreatorImpl
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
@@ -33,7 +33,7 @@ public class ElasticsearchEntityInformationCreatorImpl implements ElasticsearchE
|
||||
private final MappingContext<? extends ElasticsearchPersistentEntity<?>, ElasticsearchPersistentProperty> mappingContext;
|
||||
|
||||
public ElasticsearchEntityInformationCreatorImpl(
|
||||
MappingContext<? extends ElasticsearchPersistentEntity<?>, ElasticsearchPersistentProperty> mappingContext) {
|
||||
MappingContext<? extends ElasticsearchPersistentEntity<?>, ElasticsearchPersistentProperty> mappingContext) {
|
||||
Assert.notNull(mappingContext);
|
||||
this.mappingContext = mappingContext;
|
||||
}
|
||||
@@ -41,7 +41,7 @@ public class ElasticsearchEntityInformationCreatorImpl implements ElasticsearchE
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T, ID extends Serializable> ElasticsearchEntityInformation<T, ID> getEntityInformation(Class<T> domainClass) {
|
||||
ElasticsearchPersistentEntity<T> persistentEntity = (ElasticsearchPersistentEntity<T>) mappingContext
|
||||
ElasticsearchPersistentEntity<T> persistentEntity = (ElasticsearchPersistentEntity<T>) mappingContext
|
||||
.getPersistentEntity(domainClass);
|
||||
return new MappingElasticsearchEntityInformation<T, ID>(persistentEntity);
|
||||
}
|
||||
|
||||
@@ -35,90 +35,87 @@ import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* Factory to create {@link ElasticsearchRepository}
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
* @author Ryan Henszey
|
||||
*/
|
||||
public class ElasticsearchRepositoryFactory extends RepositoryFactorySupport {
|
||||
|
||||
|
||||
private final ElasticsearchOperations elasticsearchOperations;
|
||||
private final ElasticsearchEntityInformationCreator entityInformationCreator;
|
||||
private final ElasticsearchOperations elasticsearchOperations;
|
||||
private final ElasticsearchEntityInformationCreator entityInformationCreator;
|
||||
|
||||
public ElasticsearchRepositoryFactory(ElasticsearchOperations elasticsearchOperations) {
|
||||
Assert.notNull(elasticsearchOperations);
|
||||
this.elasticsearchOperations = elasticsearchOperations;
|
||||
this.entityInformationCreator = new ElasticsearchEntityInformationCreatorImpl(elasticsearchOperations.getElasticsearchConverter()
|
||||
.getMappingContext());
|
||||
}
|
||||
public ElasticsearchRepositoryFactory(ElasticsearchOperations elasticsearchOperations) {
|
||||
Assert.notNull(elasticsearchOperations);
|
||||
this.elasticsearchOperations = elasticsearchOperations;
|
||||
this.entityInformationCreator = new ElasticsearchEntityInformationCreatorImpl(elasticsearchOperations
|
||||
.getElasticsearchConverter().getMappingContext());
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T, ID extends Serializable> ElasticsearchEntityInformation<T, ID> getEntityInformation(Class<T> domainClass) {
|
||||
return entityInformationCreator.getEntityInformation(domainClass);
|
||||
}
|
||||
@Override
|
||||
public <T, ID extends Serializable> ElasticsearchEntityInformation<T, ID> getEntityInformation(Class<T> domainClass) {
|
||||
return entityInformationCreator.getEntityInformation(domainClass);
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
protected Object getTargetRepository(RepositoryMetadata metadata) {
|
||||
|
||||
ElasticsearchEntityInformation<?, ?> entityInformation = getEntityInformation(metadata.getDomainType());
|
||||
|
||||
AbstractElasticsearchRepository repository;
|
||||
|
||||
//Probably a better way to store and look these up.
|
||||
if(Integer.class.isAssignableFrom(entityInformation.getIdType()) ||
|
||||
Long.class.isAssignableFrom(entityInformation.getIdType()) ||
|
||||
Double.class.isAssignableFrom(entityInformation.getIdType())){
|
||||
//logger.debug("Using NumberKeyedRepository for " + metadata.getRepositoryInterface());
|
||||
repository = new NumberKeyedRepository(getEntityInformation(metadata.getDomainType()), elasticsearchOperations);
|
||||
}
|
||||
else if (entityInformation.getIdType() == String.class){
|
||||
//logger.debug("Using SimpleElasticsearchRepository for " + metadata.getRepositoryInterface());
|
||||
repository = new SimpleElasticsearchRepository(getEntityInformation(metadata.getDomainType()), elasticsearchOperations);
|
||||
}
|
||||
else {
|
||||
throw new IllegalArgumentException("Unsuppored ID type " + entityInformation.getIdType());
|
||||
}
|
||||
repository.setEntityClass(metadata.getDomainType());
|
||||
|
||||
return repository;
|
||||
}
|
||||
@Override
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
protected Object getTargetRepository(RepositoryMetadata metadata) {
|
||||
|
||||
@Override
|
||||
protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
|
||||
if (isQueryDslRepository(metadata.getRepositoryInterface())) {
|
||||
throw new IllegalArgumentException("QueryDsl Support has not been implemented yet.");
|
||||
}
|
||||
return SimpleElasticsearchRepository.class;
|
||||
}
|
||||
ElasticsearchEntityInformation<?, ?> entityInformation = getEntityInformation(metadata.getDomainType());
|
||||
|
||||
private static boolean isQueryDslRepository(Class<?> repositoryInterface) {
|
||||
return QUERY_DSL_PRESENT && QueryDslPredicateExecutor.class.isAssignableFrom(repositoryInterface);
|
||||
}
|
||||
AbstractElasticsearchRepository repository;
|
||||
|
||||
@Override
|
||||
protected QueryLookupStrategy getQueryLookupStrategy(QueryLookupStrategy.Key key) {
|
||||
return new ElasticsearchQueryLookupStrategy();
|
||||
}
|
||||
// Probably a better way to store and look these up.
|
||||
if (Integer.class.isAssignableFrom(entityInformation.getIdType())
|
||||
|| Long.class.isAssignableFrom(entityInformation.getIdType())
|
||||
|| Double.class.isAssignableFrom(entityInformation.getIdType())) {
|
||||
// logger.debug("Using NumberKeyedRepository for " + metadata.getRepositoryInterface());
|
||||
repository = new NumberKeyedRepository(getEntityInformation(metadata.getDomainType()), elasticsearchOperations);
|
||||
} else if (entityInformation.getIdType() == String.class) {
|
||||
// logger.debug("Using SimpleElasticsearchRepository for " + metadata.getRepositoryInterface());
|
||||
repository = new SimpleElasticsearchRepository(getEntityInformation(metadata.getDomainType()),
|
||||
elasticsearchOperations);
|
||||
} else {
|
||||
throw new IllegalArgumentException("Unsuppored ID type " + entityInformation.getIdType());
|
||||
}
|
||||
repository.setEntityClass(metadata.getDomainType());
|
||||
|
||||
private class ElasticsearchQueryLookupStrategy implements QueryLookupStrategy {
|
||||
return repository;
|
||||
}
|
||||
|
||||
@Override
|
||||
public RepositoryQuery resolveQuery(Method method, RepositoryMetadata metadata, NamedQueries namedQueries) {
|
||||
@Override
|
||||
protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
|
||||
if (isQueryDslRepository(metadata.getRepositoryInterface())) {
|
||||
throw new IllegalArgumentException("QueryDsl Support has not been implemented yet.");
|
||||
}
|
||||
return SimpleElasticsearchRepository.class;
|
||||
}
|
||||
|
||||
ElasticsearchQueryMethod queryMethod = new ElasticsearchQueryMethod(method, metadata, entityInformationCreator);
|
||||
String namedQueryName = queryMethod.getNamedQueryName();
|
||||
private static boolean isQueryDslRepository(Class<?> repositoryInterface) {
|
||||
return QUERY_DSL_PRESENT && QueryDslPredicateExecutor.class.isAssignableFrom(repositoryInterface);
|
||||
}
|
||||
|
||||
if (namedQueries.hasQuery(namedQueryName)) {
|
||||
String namedQuery = namedQueries.getQuery(namedQueryName);
|
||||
return new ElasticsearchStringQuery(queryMethod, elasticsearchOperations, namedQuery);
|
||||
}
|
||||
else if (queryMethod.hasAnnotatedQuery()) {
|
||||
return new ElasticsearchStringQuery(queryMethod, elasticsearchOperations, queryMethod.getAnnotatedQuery());
|
||||
}
|
||||
return new ElasticsearchPartQuery(queryMethod, elasticsearchOperations);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
protected QueryLookupStrategy getQueryLookupStrategy(QueryLookupStrategy.Key key) {
|
||||
return new ElasticsearchQueryLookupStrategy();
|
||||
}
|
||||
|
||||
private class ElasticsearchQueryLookupStrategy implements QueryLookupStrategy {
|
||||
|
||||
@Override
|
||||
public RepositoryQuery resolveQuery(Method method, RepositoryMetadata metadata, NamedQueries namedQueries) {
|
||||
|
||||
ElasticsearchQueryMethod queryMethod = new ElasticsearchQueryMethod(method, metadata, entityInformationCreator);
|
||||
String namedQueryName = queryMethod.getNamedQueryName();
|
||||
|
||||
if (namedQueries.hasQuery(namedQueryName)) {
|
||||
String namedQuery = namedQueries.getQuery(namedQueryName);
|
||||
return new ElasticsearchStringQuery(queryMethod, elasticsearchOperations, namedQuery);
|
||||
} else if (queryMethod.hasAnnotatedQuery()) {
|
||||
return new ElasticsearchStringQuery(queryMethod, elasticsearchOperations, queryMethod.getAnnotatedQuery());
|
||||
}
|
||||
return new ElasticsearchPartQuery(queryMethod, elasticsearchOperations);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -24,13 +24,14 @@ import org.springframework.util.Assert;
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* Spring {@link org.springframework.beans.factory.FactoryBean} implementation to ease container based configuration for XML namespace and JavaConfig.
|
||||
*
|
||||
* Spring {@link org.springframework.beans.factory.FactoryBean} implementation to ease container based configuration for
|
||||
* XML namespace and JavaConfig.
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
*/
|
||||
public class ElasticsearchRepositoryFactoryBean<T extends Repository<S, ID>, S, ID extends Serializable> extends
|
||||
RepositoryFactoryBeanSupport<T, S, ID> {
|
||||
RepositoryFactoryBeanSupport<T, S, ID> {
|
||||
|
||||
private ElasticsearchOperations operations;
|
||||
|
||||
@@ -50,14 +51,13 @@ public class ElasticsearchRepositoryFactoryBean<T extends Repository<S, ID>, S,
|
||||
*/
|
||||
@Override
|
||||
public void afterPropertiesSet() {
|
||||
super.afterPropertiesSet();
|
||||
super.afterPropertiesSet();
|
||||
Assert.notNull(operations, "ElasticsearchOperations must be configured!");
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected RepositoryFactorySupport createRepositoryFactory() {
|
||||
return new ElasticsearchRepositoryFactory(operations);
|
||||
}
|
||||
@Override
|
||||
protected RepositoryFactorySupport createRepositoryFactory() {
|
||||
return new ElasticsearchRepositoryFactory(operations);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -26,81 +26,82 @@ import org.springframework.data.repository.core.support.AbstractEntityInformatio
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* Elasticsearch specific implementation of {@link org.springframework.data.repository.core.support.AbstractEntityInformation}
|
||||
*
|
||||
* Elasticsearch specific implementation of
|
||||
* {@link org.springframework.data.repository.core.support.AbstractEntityInformation}
|
||||
*
|
||||
* @param <T>
|
||||
* @param <ID>
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
* @author Ryan Henszey
|
||||
*/
|
||||
public class MappingElasticsearchEntityInformation<T, ID extends Serializable> extends AbstractEntityInformation<T, ID>
|
||||
implements ElasticsearchEntityInformation<T, ID> {
|
||||
implements ElasticsearchEntityInformation<T, ID> {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MappingElasticsearchEntityInformation.class);
|
||||
private final ElasticsearchPersistentEntity<T> entityMetadata;
|
||||
private final String indexName;
|
||||
private final String type;
|
||||
private Class<?> idClass;
|
||||
private static final Logger logger = LoggerFactory.getLogger(MappingElasticsearchEntityInformation.class);
|
||||
private final ElasticsearchPersistentEntity<T> entityMetadata;
|
||||
private final String indexName;
|
||||
private final String type;
|
||||
private Class<?> idClass;
|
||||
|
||||
public MappingElasticsearchEntityInformation(ElasticsearchPersistentEntity<T> entity) {
|
||||
this(entity, null, null);
|
||||
}
|
||||
public MappingElasticsearchEntityInformation(ElasticsearchPersistentEntity<T> entity) {
|
||||
this(entity, null, null);
|
||||
}
|
||||
|
||||
public MappingElasticsearchEntityInformation(ElasticsearchPersistentEntity<T> entity, String indexName, String type) {
|
||||
super(entity.getType());
|
||||
this.entityMetadata = entity;
|
||||
this.indexName = indexName;
|
||||
this.type = type;
|
||||
this.idClass = entity.getIdProperty().getType();
|
||||
}
|
||||
public MappingElasticsearchEntityInformation(ElasticsearchPersistentEntity<T> entity, String indexName, String type) {
|
||||
super(entity.getType());
|
||||
this.entityMetadata = entity;
|
||||
this.indexName = indexName;
|
||||
this.type = type;
|
||||
this.idClass = entity.getIdProperty().getType();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public ID getId(T entity) {
|
||||
ElasticsearchPersistentProperty id = entityMetadata.getIdProperty();
|
||||
try {
|
||||
return (ID) BeanWrapper.create(entity, null).getProperty(id);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("ID could not be resolved", e);
|
||||
}
|
||||
}
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public ID getId(T entity) {
|
||||
ElasticsearchPersistentProperty id = entityMetadata.getIdProperty();
|
||||
try {
|
||||
return (ID) BeanWrapper.create(entity, null).getProperty(id);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("ID could not be resolved", e);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public Class<ID> getIdType() {
|
||||
return (Class<ID>)idClass;
|
||||
}
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public Class<ID> getIdType() {
|
||||
return (Class<ID>) idClass;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getIdAttribute() {
|
||||
Assert.notNull(entityMetadata.getIdProperty(),"Unable to identify 'id' property in class " + entityMetadata.getType().getSimpleName() +". Make sure the 'id' property is annotated with @Id or named as 'id' or 'documentId' ");
|
||||
return entityMetadata.getIdProperty().getFieldName();
|
||||
}
|
||||
@Override
|
||||
public String getIdAttribute() {
|
||||
Assert.notNull(entityMetadata.getIdProperty(), "Unable to identify 'id' property in class "
|
||||
+ entityMetadata.getType().getSimpleName()
|
||||
+ ". Make sure the 'id' property is annotated with @Id or named as 'id' or 'documentId' ");
|
||||
return entityMetadata.getIdProperty().getFieldName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getIndexName() {
|
||||
return indexName != null? indexName : entityMetadata.getIndexName();
|
||||
}
|
||||
@Override
|
||||
public String getIndexName() {
|
||||
return indexName != null ? indexName : entityMetadata.getIndexName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getType() {
|
||||
return type != null? type : entityMetadata.getIndexType();
|
||||
}
|
||||
@Override
|
||||
public String getType() {
|
||||
return type != null ? type : entityMetadata.getIndexType();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long getVersion(T entity) {
|
||||
ElasticsearchPersistentProperty versionProperty = entityMetadata.getVersionProperty();
|
||||
try {
|
||||
if(versionProperty != null){
|
||||
return (Long) BeanWrapper.create(entity, null).getProperty(versionProperty);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("failed to load version field", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@Override
|
||||
public Long getVersion(T entity) {
|
||||
ElasticsearchPersistentProperty versionProperty = entityMetadata.getVersionProperty();
|
||||
try {
|
||||
if (versionProperty != null) {
|
||||
return (Long) BeanWrapper.create(entity, null).getProperty(versionProperty);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("failed to load version field", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -18,34 +18,32 @@ package org.springframework.data.elasticsearch.repository.support;
|
||||
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
|
||||
|
||||
/**
|
||||
* Elasticsearch specific repository implementation. Likely to be used as target within {@link ElasticsearchRepositoryFactory}
|
||||
*
|
||||
*
|
||||
* Elasticsearch specific repository implementation. Likely to be used as target within
|
||||
* {@link ElasticsearchRepositoryFactory}
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
* @author Ryan Henszey
|
||||
*/
|
||||
public class NumberKeyedRepository<T,ID extends Number> extends AbstractElasticsearchRepository<T,ID> {
|
||||
public class NumberKeyedRepository<T, ID extends Number> extends AbstractElasticsearchRepository<T, ID> {
|
||||
|
||||
|
||||
public NumberKeyedRepository() {
|
||||
super();
|
||||
}
|
||||
public NumberKeyedRepository() {
|
||||
super();
|
||||
}
|
||||
|
||||
public NumberKeyedRepository(ElasticsearchEntityInformation<T, ID> metadata,ElasticsearchOperations elasticsearchOperations) {
|
||||
super(metadata, elasticsearchOperations);
|
||||
}
|
||||
public NumberKeyedRepository(ElasticsearchEntityInformation<T, ID> metadata,
|
||||
ElasticsearchOperations elasticsearchOperations) {
|
||||
super(metadata, elasticsearchOperations);
|
||||
}
|
||||
|
||||
public NumberKeyedRepository(ElasticsearchOperations elasticsearchOperations) {
|
||||
super(elasticsearchOperations);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
protected String stringIdRepresentation(ID id) {
|
||||
return String.valueOf(id);
|
||||
}
|
||||
|
||||
public NumberKeyedRepository(ElasticsearchOperations elasticsearchOperations) {
|
||||
super(elasticsearchOperations);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String stringIdRepresentation(ID id) {
|
||||
return String.valueOf(id);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -18,30 +18,32 @@ package org.springframework.data.elasticsearch.repository.support;
|
||||
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
|
||||
|
||||
/**
|
||||
* Elasticsearch specific repository implementation. Likely to be used as target within {@link ElasticsearchRepositoryFactory}
|
||||
*
|
||||
*
|
||||
* Elasticsearch specific repository implementation. Likely to be used as target within
|
||||
* {@link ElasticsearchRepositoryFactory}
|
||||
*
|
||||
*
|
||||
* @author Rizwan Idrees
|
||||
* @author Mohsin Husen
|
||||
* @author Ryan Henszey
|
||||
*/
|
||||
public class SimpleElasticsearchRepository<T> extends AbstractElasticsearchRepository<T,String> {
|
||||
|
||||
public SimpleElasticsearchRepository() {
|
||||
super();
|
||||
}
|
||||
public class SimpleElasticsearchRepository<T> extends AbstractElasticsearchRepository<T, String> {
|
||||
|
||||
public SimpleElasticsearchRepository(ElasticsearchEntityInformation<T, String> metadata,ElasticsearchOperations elasticsearchOperations) {
|
||||
super(metadata, elasticsearchOperations);
|
||||
}
|
||||
public SimpleElasticsearchRepository() {
|
||||
super();
|
||||
}
|
||||
|
||||
public SimpleElasticsearchRepository(ElasticsearchOperations elasticsearchOperations) {
|
||||
super(elasticsearchOperations);
|
||||
}
|
||||
public SimpleElasticsearchRepository(ElasticsearchEntityInformation<T, String> metadata,
|
||||
ElasticsearchOperations elasticsearchOperations) {
|
||||
super(metadata, elasticsearchOperations);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String stringIdRepresentation(String id) {
|
||||
return id;
|
||||
}
|
||||
public SimpleElasticsearchRepository(ElasticsearchOperations elasticsearchOperations) {
|
||||
super(elasticsearchOperations);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String stringIdRepresentation(String id) {
|
||||
return id;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user