我正在使用Spring Data Cassandra 1.0.0。我设法坚持并回读我的实体。但是,现在我想做一个只返回实体的1个字段的查询。
这就是我的尝试:
public Optional<DateTime> getTimeOfOldestIntervalTrafficDataMessage( MessageSource messageSource, IntegrationPeriod integrationPeriod, TrafficDataType trafficDataType )
{
Select select = QueryBuilder.select( "message_time" ).from( "messages", "data_message" );
select.where( QueryBuilder.eq( "message_source_id", messageSource.getId().getId() ) )
.and( QueryBuilder.eq( "data_type", trafficDataType.name() ) )
.and( QueryBuilder.eq( "integration_period", integrationPeriod.name() ) );
List<Date> result = cassandraOperations.select( select, Date.class );
if (result.size() > 0)
{
return Optional.of( new DateTime( FluentIterable.from( result ).toSortedSet( Ordering.natural() ).first() ) );
}
else
{
return Optional.absent();
}
}
cassandraOperations
是CassandraTemplate
个实例。
所以我只从message_time
表中选择data_message
。这是一个timestamp
列,因此我将Date.class
传递给select()
方法,但这会产生以下异常:
org.springframework.data.mapping.model.MappingException: No mapping metadata found for java.util.Date
at org.springframework.data.cassandra.convert.MappingCassandraConverter.readRow(MappingCassandraConverter.java:111)
at org.springframework.data.cassandra.convert.MappingCassandraConverter.read(MappingCassandraConverter.java:202)
at org.springframework.data.cassandra.core.CassandraConverterRowCallback.doWith(CassandraConverterRowCallback.java:47)
at org.springframework.data.cassandra.core.CassandraTemplate.select(CassandraTemplate.java:455)
at org.springframework.data.cassandra.core.CassandraTemplate.select(CassandraTemplate.java:253)
at com.mycomp.app.infrastructure.cassandra.CassandraMessageRepository.getTimeOfOldestIntervalTrafficDataMessage(CassandraMessageRepository.java:130)
我应该如何查询1个字段?
PS:如果您知道一种更高效的方式来进行此查询,我也很乐意听到它。
答案 0 :(得分:6)
了解如何操作:
public Optional<DateTime> getTimeOfOldestIntervalTrafficDataMessage( MessageSource messageSource, IntegrationPeriod integrationPeriod, TrafficDataType trafficDataType )
{
Select select = QueryBuilder.select( "message_time" ).from( "messages", "data_message" );
select.where( QueryBuilder.eq( "message_source_id", messageSource.getId().getId() ) )
.and( QueryBuilder.eq( "traffic_data_type", trafficDataType.name() ) )
.and( QueryBuilder.eq( "integration_period", integrationPeriod.name() ) );
select.orderBy( QueryBuilder.asc( "message_time" ) );
select.limit( 1 );
Date date = m_cassandraOperations.queryForObject( select, Date.class );
if( date != null )
{
Optional<DateTime> result = Optional.of( new DateTime( date ) );
logger.debug( "oldest interval: {} ({}/{}/{})", result, messageSource.getName(), trafficDataType, integrationPeriod );
return result;
}
else
{
return Optional.absent();
}
}
queryForObject()
功能是要走的路。我还使用了排序和限制来让Cassandra做我需要的工作。