使用Spring Data Mongodb中的Query类进行不区分大小写的排序。

huangapple go评论79阅读模式
英文:

Case-insensitive sort using Query class in Spring Data Mongodb

问题

// 使用这种类型的排序,并且我想要大小写不敏感。

Query query = new Query();
query.with(new Sort(new Order(Sort.Direction.ASC, "title").ignoreCase()));
return db.find(query, Video.class);

我尝试了这个查询但没有得到任何结果

所使用的导入

import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;


例如如果我有这种类型的标题
"Inception""BlackList""adore""123""city""desperadoS"

排序应该是
"123""adore""BlackList""city""desperadoS""Inception"

如果我这样使用

Query query = new Query();
query.with(new Sort(Sort.Direction.ASC, "title"));
return db.find(query, Video.class);

它返回

"123""BlackList""Inception""adore""city""desperadoS"

Spring-data-mongodb 版本 1.9.2
英文:

I am using this type of sorting, and I want to be case insensitive.

            Query query = new Query();
			query.with(new Sort(new Order(Sort.Direction.ASC,"title").ignoreCase()));
			return db.find(query, Video.class);

I tried this query but I don't get any results back.

Imports used:

import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

For example, if I have this type of titles:
"Inception","BlackList","adore","123", "city","desperadoS"

The order should be:
"123","adore","BlackList","city","desperadoS","Inception"

If i use it this way

        Query query = new Query();
		query.with(new Sort(Sort.Direction.ASC,"title"));
		return db.find(query, Video.class);

It returns

"123","BlackList","Inception","adore","city","desperadoS"

Spring-data-mongodb version 1.9.2

答案1

得分: 1

Here is the translation of the code snippet you provided:

另一种方法是使用 @Query 注解与 Collation 一起来获取期望的排序顺序:"123","adore","BlackList","city","desperadoS","Inception"

文档

@Document(collection = "video")
@Data
public class Video {

    @Id
    private String id;
    private String title;

    public Video(String title) {
        this.title = title;
    }
}

仓库

@Repository
public interface VideoRepository extends MongoRepository<Video, String> {

    @Query(collation = "en", value = "{}")
    List<Video> getAllSortedVideos(Sort sort);

}

集成测试类以断言更改

@ActiveProfiles("test")
@SpringBootTest(classes = DemoApplication.class, 
        webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class VideoRepositoryITest {

    @Autowired
    private VideoRepository videoRepository;

    @Test
    void getAllSortedVideos() {
        List<String> expectedSystemNamesInOrder = Arrays.asList("123", "adore", "BlackList",
                                                    "city", "desperadoS", "Inception");
        // 打乱顺序以增加趣味性
        Set<String> expectedSystemNamesSet = new HashSet<>(expectedSystemNamesInOrder);
        // 保存每个标题的视频
        expectedSystemNamesSet.stream().map(Video::new)
                .forEach(videoRepository::save);
        // 按标题获取已排序的视频
        List<Video> videos = videoRepository.getAllSortedVideos(Sort.by(Direction.ASC, "title"));
        // 获取已排序的视频标题以进行断言
        List<String> titles = videos.stream().map(Video::getTitle).collect(Collectors.toList());
        // 使用期望的顺序断言结果视频标题的顺序
        for (int i = 0; i < titles.size(); i++) {
            String actualTitle = titles.get(i);
            String expectedTitle = expectedSystemNamesInOrder.get(i);
            // 如果检索到的标题顺序与期望的顺序不匹配,测试用例将失败
            Assertions.assertEquals(expectedTitle, actualTitle);
        }
    }

}

使用 org.springframework.data:spring-data-mongodb:3.0.4.RELEASE

英文:

Another approach to use Collation with @Query annotation to get the expected sorting order of &quot;123&quot;,&quot;adore&quot;,&quot;BlackList&quot;,&quot;city&quot;,&quot;desperadoS&quot;,&quot;Inception&quot;

Document

@Document(collection = &quot;video&quot;)
@Data
public class Video {

    @Id
    private String id;
    private String title;

    public Video(String title) {
        this.title = title;
    }
}

Repository

@Repository
public interface VideoRepository extends MongoRepository&lt;Video, String&gt; {

    @Query(collation = &quot;en&quot;, value = &quot;{}&quot;)
    List&lt;Video&gt; getAllSortedVideos(Sort sort);

}

Integration Test class to assert the changes

@ActiveProfiles(&quot;test&quot;)
@SpringBootTest(classes = DemoApplication.class, 
        webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class VideoRepositoryITest {

    @Autowired
    private VideoRepository videoRepository;

    @Test
    void getAllSortedVideos() {
        List&lt;String&gt; expectedSystemNamesInOrder = Arrays.asList(&quot;123&quot;, &quot;adore&quot;, &quot;BlackList&quot;,
                                                    &quot;city&quot;, &quot;desperadoS&quot;, &quot;Inception&quot;);
        //breaking the order for fun
        Set&lt;String&gt; expectedSystemNamesSet = new HashSet&lt;&gt;(expectedSystemNamesInOrder);
        //saving the videos of each title
        expectedSystemNamesSet.stream().map(Video::new)
                .forEach(videoRepository::save);
        //fetching sorted Videos by title
        List&lt;Video&gt; videos = videoRepository.getAllSortedVideos(Sort.by(Direction.ASC, &quot;title&quot;));
        //fetching sorted Video tiles to assert
        List&lt;String&gt; titles = videos.stream().map(Video::getTitle).collect(Collectors.toList());
        //asserting the result video title order with the expected order
        for (int i = 0; i &lt; titles.size(); i++) {
            String actualTitle = titles.get(i);
            String expectedTitle = expectedSystemNamesInOrder.get(i);
            //Test case will fail if the retrieved title order doesn&#39;t match with expected order
            Assertions.assertEquals(expectedTitle, actualTitle);
        }
    }

}

Using org.springframework.data:spring-data-mongodb:3.0.4.RELEASE

答案2

得分: 0

使用排序规则来进行不区分大小写的排序。
示例在这里

当使用new Order(Sort.Direction.ASC,"title").ignoreCase())时,将会抛出IllegalArgumentException异常。

在您的情况下:

Query query = new Query().with(Sort.by(new Sort.Order(Sort.Direction.ASC, "title")));
query.collation(Collation.of("en").strength(Collation.ComparisonLevel.secondary()));
return mongoTemplate.find(query, Video.class);
英文:

Use collation to sort ignoring cases.
Example is here

You will get an IllegalArgumentException, when use
new Order(Sort.Direction.ASC,&quot;title&quot;).ignoreCase())

In your case:

Query query = new Query().with(Sort.by(new Sort.Order(Sort.Direction.ASC, &quot;title&quot;)));
query.collation(Collation.of(&quot;en&quot;).strength(Collation.ComparisonLevel.secondary()));
return mongoTemplate.find(query, Video.class);

huangapple
  • 本文由 发表于 2020年8月12日 16:24:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/63372662.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定