Spring Data - MongoDB - $regex搜索

3

我在我的应用程序中使用Spring Data和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);

...
}

This method I invoke like this:

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/吗?

2个回答

7

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

对于Java驱动程序,您只需要使用"^Wand"

尝试一下

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

更多内容请戳这里


0
你可能还需要引用:
public static String escapeForRegex(String input) {
    return input.replace("\\", "\\\\")
                .replace(".", "\\.")
                .replace("*", "\\*")
                .replace("+", "\\+")
                .replace("?", "\\?")
                .replace("{", "\\{")
                .replace("}", "\\}")
                .replace("(", "\\(")
                .replace(")", "\\)")
                .replace("[", "\\[")
                .replace("]", "\\]")
                .replace("^", "\\^")
                .replace("$", "\\$")
                .replace("|", "\\|");
}

Pattern.quote(input)以更好的方式完成了这个任务。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接