gpt4 book ai didi

regex - Spring 数据 - MongoDB - $regex 搜索

转载 作者:可可西里 更新时间:2023-11-01 10:13:11 24 4
gpt4 key购买 nike

我在我的应用程序中使用 Spring 数据和 MongoDB,我的一个存储库类如下所示:

public interface ProductRepository extends MongoRepository<Product, String> {

@Query("{$or : [{'name': { $regex: ?0, $options:'i' }}, {'description': { $regex: ?0, $options:'i' }}]}")
List<Product> findProductByRegexString(final String regexString);

...
}

我这样调用这个方法:

public class ProductServiceTest extends AbstractServiceTest {

@Test
public void shouldSearchProductBySubString() throws BusinessException {

final Tenant tenant = new Tenant();
tenant.setName("TestTenant");
final Tenant createdTenant = tenantService.create(tenant);
Assert.assertNotNull(createdTenant);

final Product product1 = new Product();
product1.setName("Wander");
product1.setDescription("Das ist das Test Produkt 1");
product1.setTenant(createdTenant);
final Product createdProduct1 = productService.create(product1);
Assert.assertNotNull(createdProduct1);

final Product product2 = new Product();
product2.setName("Wunder baum");
product2.setDescription("Ein different Produkt 2");
product2.setTenant(createdTenant);
final Product createdProduct2 = productService.create(product2);
Assert.assertNotNull(createdProduct2);

final List<Product> allProducts = productService.findAllProductsByTenant(createdTenant);
Assert.assertEquals(2, allProducts.size());

final List<Product> products = productService.findProductsByRegex("/^Wand/");
Assert.assertEquals(1, products.size());
}
}

而且效果很好。如果我尝试使用这个字符:

regex

例如:

final List<Product> products = productService.findProductsByRegex("/^Wand/");

我没有得到字符串 /^Wand/ 的任何结果有没有人有任何解释为什么它不适用于 /^Wand/

最佳答案

/expression/ 是 shell 和 js 驱动程序中使用的替代语法。

对于 java 驱动你只需要使用 "^Wand"

尝试

final List<Product> products = productService.findProductsByRegex("^Wand");

更多here

关于regex - Spring 数据 - MongoDB - $regex 搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48424222/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com