# Búsquedas Expresiones Regulares (Patrones Like)

## Búsquedas Expresiones Regulares (Regex)

Se utilizan para consultas mediante patrones. Funcionan de manera similar a las sentencias like en el modelo relacional en donde generalmente usamos el comodín "%s" para ampliar las operaciones de búsquedas.

Es una implementación de regex en mongodb

```
https://docs.mongodb.com/manual/reference/operator/query/regex
```

**Método:**

| Método                                                                                                                                                                                                                             | Bases de datos NoSQL (MongoDB)                                                                                                                           |                                                                                                                            |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| public List< T > **findRegex**(String key, String value, Document... docSort)                                                                                                                                                      | MongoDB                                                                                                                                                  | Busca en el texto desde el inicio que coincida con la expresion                                                            |
| public List\<T> **findRegexInText**(String key, String value, Boolean caseSensitive, Document... docSort)                                                                                                                          | MongoDB                                                                                                                                                  | Busca en cualquier parte del Texto                                                                                         |
| public List\<T> **findRegexPagination**(String key, String value, Boolean caseSensitive, Integer pageNumber, Integer rowsForPage,Document... docSort)                                                                              | MongoDB                                                                                                                                                  | Busca en el texto desde el inicio que coincida con la expresión con paginación.                                            |
| public List\<T> **findRegexInTextPagination**(String key, String value, Boolean caseSensitive, Integer pageNumber, Integer rowsForPage, Document... docSort)                                                                       | MongoDB                                                                                                                                                  | Busca en cualquier parte del texto con paginación                                                                          |
|                                                                                                                                                                                                                                    | **Filtros agregando por una condición and adicional(String keySecond,String valueSecond)**                                                               |                                                                                                                            |
| List\<T> **findRegex(**&#x53;tring key, String value, Boolean caseSensitive, **String keySecond,String valueSecond**,Document... docSort)                                                                                          | MongoDB                                                                                                                                                  | Busca en el texto desde el inicio que coincida con la expresión y agrega un filtro and adicional por otro atributo.        |
| List\<T> **findRegexInTex**t(String key, String value, Boolean caseSensitive, **String keySecond,String valueSecond**, Document... docSort)                                                                                        | MongoDB                                                                                                                                                  | Busca en cualquier parte del texto agregando un filtro and por otro atributo.                                              |
| List\<T> **findRegexPagination**(String key, String value, Boolean caseSensitive,**String keySecond,String valueSecond,** Integer pageNumber, Integer rowsForPage,Document... docSort)                                             | MongoDB                                                                                                                                                  | Busca en el texto desde el inicio que coincida con la expresión con paginación, agregando un filtro and por otro atributo. |
| List\<T> **findRegexInTextPagination**(String key, String value, Boolean caseSensitive, **String keySecond,String valueSecond,**&#x49;nteger pageNumber, Integer rowsForPage, Document... docSort)                                 | MongoDB                                                                                                                                                  | Busca en cualquier parte del texto agregando un filtro and adicional por otro atributo y aplica paginación.                |
|                                                                                                                                                                                                                                    | **Filtros agregando por una condición and adicional(String keySecond,Object valueSecond). El valueSecond puede ser tipo String, Integer, Double, Date.** |                                                                                                                            |
| List\<T> **findRegex**(String key, String value, Boolean caseSensitive, S**tring keySecond**, **Object valueSecond**, Document... docSort)                                                                                         | MongoDB                                                                                                                                                  | Busca en el texto desde el inicio que coincida con la expresión y agrega un filtro and adicional por otro atributo.        |
|                                                                                                                                                                                                                                    | Filtros agregando dos condiciónes and adicional(String keySecond,O**bject valueSecond**,**Object keyThree,** String valueTree)                           |                                                                                                                            |
|                                                                                                                                                                                                                                    |                                                                                                                                                          |                                                                                                                            |
|                                                                                                                                                                                                                                    |                                                                                                                                                          |                                                                                                                            |
|                                                                                                                                                                                                                                    | Filtros agregando dos condiciónes and adicional(**String keySecond,String valueSecond,String keyThree, String valueTree)**                               |                                                                                                                            |
| List\<T> **findRegex**(String key, String value, Boolean caseSensitive, **String keySecond, String valueSecond,** **String keyThree, String valueTree,** Document... docSort)                                                      | MongoDB                                                                                                                                                  | Busca en el texto desde el inicio que coincida con la expresión y agrega dos flltros and adicionales                       |
| List\<T> **findRegexInText**(String key, String value, Boolean caseSensitive, **String keySecond, String valueSecond,String keyThree, String valueTree**, Document... docSort)                                                     | MongoDB                                                                                                                                                  | Busca en cualquier parte del texto agregando dos filtros and adicionales.                                                  |
| List\<T> **findRegexPagination**(String key, String value, Boolean caseSensitive, **String keySecond, String valueSecond, String keyThree, String valueThree**,Integer pageNumber, Integer rowsForPage, Document... docSort)       | MongoDB                                                                                                                                                  | Busca en el texto desde el inicio que coincida con la expresión con paginación, agregando dos filtros and adicionales.     |
| List\<T> **findRegexInTextPagination**(String key, String value, Boolean caseSensitive, **String keySecond, String valueSecond,String keyThree, String valueThree**, Integer pageNumber, Integer rowsForPage, Document... docSort) | MongoDB                                                                                                                                                  | Busca en cualquier parte del texto agregando dos filtros and adicional por otro atributo y aplica paginación.              |
|                                                                                                                                                                                                                                    |                                                                                                                                                          |                                                                                                                            |

**Nota:** Para bases de datos couchbase puede ser el método find() en el statement puede colocar el filtro.

### $regex

| **Simbolo**  |                                         |
| ------------ | --------------------------------------- |
| $regex: "Pa" | Busca que tengan el carácter  Pa        |
| ^pana$       | Busca el texto que inicia ^ y termina $ |

### $options

| **Simbolo** |                                             |
| ----------- | ------------------------------------------- |
| i           | Busca sin importar en mayúscula y minúscula |
|             |                                             |

### **Ejemplo MongoDB:**&#x20;

**Buscar un país que inicie con pan.**

```java
List< Paises > list = personaRepository.findRegex("pais", "pan");
```

**Buscar un país que inicie con pan y que activo =si**

```java
List< Persona > list = personaRepository.findRegex("pais", "pan","activo","si");
```

**Buscar un país que inicie con pan y devuelva la lista de entitys ordenados**

```java
List< Paises > list = paisesRepository.findRegex("pais","pan",true,new Document("pais",1));
```

**Filtra por la expresión regular. grupo que inicia por Mx y que activo sea igual a si**

```java
suggestions=  articuloRepository.findRegex("grupo","Mx",true,"activo","si",new Document(field,1));
```

### Busca en el documento referenciado "articulo.idarticulo", que inicie por el valor en el atributo query.

```java
String query="1-x";
 List<Inventario> list = inventarioRepository.findRegex("articulo.idarticulo", query, true, new Document(field, 1));
```

### Ejemplo con Filter(Busca por expresion regular en articulo.idarticulo y aplica dos filtros más (Solo String para otros tipos de valores use Filter)

```java
  List<Inventario> list = inventarioRepository.findRegex("articulo.idarticulo", query, true, "id", bodegaSelected.getIdbodega(), "tipoid", "bodega", new Document(field, 1));
```

### Ejemplo con Filter(Busca por expresion regular en articulo.idarticulo y aplica dos filtros más

```java
 Bson filter =Filters.and(Filters.eq("id",bodegaSelected.getIdbodega()), Filters.eq("tipoid","bodega"));
 List<Inventario> ist = inventarioRepository.findRegex("articulo.idarticulo", query, true, filter, new Document(field, 1));onsola
```

Creamos una colección llamada aulas

#### Mostrar todos

```
db.aulas.find()
```

Resultado

```
{ "_id" : ObjectId("58d099b6bea22215f5f24db7"), "idaula" : "PE-1", "maximo" : 40, "matriculados" : 4, "anio" : 2017 }
{ "_id" : ObjectId("58d099c1bea22215f5f24db8"), "idaula" : "PE-2", "maximo" : 40, "matriculados" : 0, "anio" : 2017 }
{ "_id" : ObjectId("58d099cbbea22215f5f24db9"), "idaula" : "PE-3", "maximo" : 40, "matriculados" : 0, "anio" : 2017 }
{ "_id" : ObjectId("58d099debea22215f5f24dba"), "idaula" : "PE-4", "maximo" : 40, "matriculados" : 3, "anio" : 2017 }
{ "_id" : ObjectId("58d099e7bea22215f5f24dbb"), "idaula" : "PE-5", "maximo" : 40, "matriculados" : 0, "anio" : 2017 }
{ "_id" : ObjectId("58d099f1bea22215f5f24dbc"), "idaula" : "PE-6", "maximo" : 40, "matriculados" : 0, "anio" : 2017 }
{ "_id" : ObjectId("58d099febea22215f5f24dbd"), "idaula" : "PD-2", "maximo" : 40, "matriculados" : 0, "anio" : 2017 }
{ "_id" : ObjectId("58d09a22bea22209d62eeec9"), "idaula" : "PD-3", "maximo" : 40, "matriculados" : 0, "anio" : 2017 }
{ "_id" : ObjectId("58d09a33bea22209d62eeeca"), "idaula" : "PD-4", "maximo" : 40, "matriculados" : 0, "anio" : 2017 }
{ "_id" : ObjectId("58d09a39bea22209d62eeecb"), "idaula" : "PD-5", "maximo" : 40, "matriculados" : 0, "anio" : 2017 }
{ "_id" : ObjectId("58d09a40bea22209d62eeecc"), "idaula" : "PD-6", "maximo" : 40, "matriculados" : 0, "anio" : 2017 }
{ "_id" : ObjectId("58d09a47bea22209d62eeecd"), "idaula" : "PD-7", "maximo" : 40, "matriculados" : 0, "anio" : 2017 }
{ "_id" : ObjectId("58d09aadbea22209d62eeece"), "idaula" : "CE-1", "maximo" : 40, "matriculados" : 0, "anio" : 2017 }
{ "_id" : ObjectId("58d09ab9bea22209d62eeecf"), "idaula" : "CE-13", "maximo" : 40, "matriculados" : 0, "anio" : 2017 }
{ "_id" : ObjectId("58d09ac1bea22209d62eeed0"), "idaula" : "CE-14", "maximo" : 40, "matriculados" : 0, "anio" : 2017 }
{ "_id" : ObjectId("58d09ac8bea22209d62eeed1"), "idaula" : "CE-15", "maximo" : 40, "matriculados" : 0, "anio" : 2017 }
{ "_id" : ObjectId("58d09ad0bea22209d62eeed2"), "idaula" : "CE-16", "maximo" : 40, "matriculados" : 0, "anio" : 2017 }
```

**Buscar los que inician con CE**

```
db.aulas.find( {idaula: { $regex: "CE" }}  )
```

**Resultado**

```
{ "_id" : ObjectId("58d09aadbea22209d62eeece"), "idaula" : "CE-1", "maximo" : 40, "matriculados" : 0, "anio" : 2017 }
{ "_id" : ObjectId("58d09ab9bea22209d62eeecf"), "idaula" : "CE-13", "maximo" : 40, "matriculados" : 0, "anio" : 2017 }
{ "_id" : ObjectId("58d09ac1bea22209d62eeed0"), "idaula" : "CE-14", "maximo" : 40, "matriculados" : 0, "anio" : 2017 }
{ "_id" : ObjectId("58d09ac8bea22209d62eeed1"), "idaula" : "CE-15", "maximo" : 40, "matriculados" : 0, "anio" : 2017 }
{ "_id" : ObjectId("58d09ad0bea22209d62eeed2"), "idaula" : "CE-16", "maximo" : 40, "matriculados" : 0, "anio" : 2017 }
```

**Buscar CE-13**

```
db.aulas.find( {idaula: { $regex: "CE-13" }}  )
```

**Resultado**

```
{ "_id" : ObjectId("58d09ab9bea22209d62eeecf"), "idaula" : "CE-13", "maximo" : 40, "matriculados" : 0, "anio" : 2017 }
```

**Usando / / buscar todos que inicien con CE-**

```
db.aulas.find( {idaula: { $regex: /CE-/ }}  )
```

**Resultado**

```
{ "_id" : ObjectId("58d09aadbea22209d62eeece"), "idaula" : "CE-1", "maximo" : 40, "matriculados" : 0, "anio" : 2017 }
{ "_id" : ObjectId("58d09ab9bea22209d62eeecf"), "idaula" : "CE-13", "maximo" : 40, "matriculados" : 0, "anio" : 2017 }
{ "_id" : ObjectId("58d09ac1bea22209d62eeed0"), "idaula" : "CE-14", "maximo" : 40, "matriculados" : 0, "anio" : 2017 }
{ "_id" : ObjectId("58d09ac8bea22209d62eeed1"), "idaula" : "CE-15", "maximo" : 40, "matriculados" : 0, "anio" : 2017 }
{ "_id" : ObjectId("58d09ad0bea22209d62eeed2"), "idaula" : "CE-16", "maximo" : 40, "matriculados" : 0, "anio" : 2017 }
```

**Buscar cE-1 exactamente**

```
db.aulas.find( {idaula: { $regex: /cE-1$/ }}  )
```

#### Resultado

> Vacio no devuelve nada porque no existe cE-1 existe CE-1

**Buscar  cE-1 ignorando mayúsculas y minúsculas**

```
 db.aulas.find( {idaula: { $regex: /cE-1$/i }}  )
```

Resultado

```
{ "_id" : ObjectId("58d09aadbea22209d62eeece"), "idaula" : "CE-1", "maximo" : 40, "matriculados" : 0, "anio" : 2017 }
```

```
```

**Ejemplo de uso**

Busca las aulas que tengan los caracteres ce, el parámetro true indica que se pueda buscar sin importar mayúscula o minúsculas.

List\<Aulas> list = aulasFacade.findRegex("idaula", "ce",true,new Document("idaula",1));

## Uso con autocomplete

```java
public List<Articulo> complete(String query) {


        List<Articulo> suggestions = new ArrayList<>();
           try {
               query = query.trim();
               if (query.length() < 1) {
                   return suggestions;
               }  
               String field = (String) UIComponent.getCurrentComponent(FacesContext.getCurrentInstance()).getAttributes().get("field");               
               suggestions=  articuloRepository.findRegex(field,query,true,new Document(field,1));

           } catch (Exception e) {
                    JsfUtil.errorMessage("complete() " + e.getLocalizedMessage());
           }
           return suggestions;
    }
```

### Ejemplo de autocompletes relacionados con findRegex()

El autocomplete distrito depende al autocomplete provincia

![](https://1490144122-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Lc1Wg6bBVlJX-GjApa1%2F-Lc1WhtDA-TTmZ6My9OJ%2F-Lc1Wv88mMAG5eXwm7XP%2Frelaciona.png?generation=1554820611057133\&alt=media)

**Crear los autocomplete**

* El segundo autocomplete el método complete se personaliza en el controller

```
<p:outputLabel value="#{msg['field.provincia']}"/>


                        <p:autoComplete     dropdown="false"    
                                            scrollHeight="250"   
                                            size="35" 
                                            emptyMessage="#{app['info.nohayregistros']}" 
                                            value="#{fiadorController.fiador.provincia}"  
                                            completeMethod="#{provinciaController.provinciaServices.complete}"    
                                            var="p"
                                            required="true"
                                            itemLabel="#{p.provincia}"
                                            itemValue="#{p}" 
                                            forceSelection="true"> 
                            <f:converter binding="#{provinciaConverter}"/>
                            <f:attribute name="field" value="provincia"/>
                            <p:ajax event="itemSelect" listener="#{provinciaController.handleSelect}"
                                    update="form:"  />  
                            <f:facet name="itemtip">
                                <h:panelGrid columns="1" cellpadding="5">

                                    <h:outputText value="#{msg['field.provincia']} #{p.provincia}" />
                                    <h:outputText value="#{msg['field.idprovincia']} #{p.idprovincia}" />

                                </h:panelGrid>
                            </f:facet>
                        </p:autoComplete>  

                        <p:outputLabel value="#{msg['field.distrito']}"/>


                        <p:autoComplete     dropdown="false" 
                                            id="distrito"
                                            scrollHeight="250"   
                                            size="25" 
                                            emptyMessage="#{app['info.nohayregistros']}" 
                                            value="#{fiadorController.fiador.distrito}"  
                                            completeMethod="#{fiadorController.completeDistrito}"    
                                            var="p"
                                            required="#{true}"
                                            itemLabel="#{p.distrito}"
                                            itemValue="#{p}" 
                                            forceSelection="true"> 
                            <f:converter binding="#{distritoConverter}"/>
                            <f:attribute name="field" value="distrito"/>
                            <p:ajax event="itemSelect" listener="#{distritoController.handleSelect}"
                                    />  
                            <f:facet name="itemtip">
                                <h:panelGrid columns="1" cellpadding="5">

                                    <h:outputText value="#{msg['field.distrito']} #{p.distrito}" />
                                    <h:outputText value="#{msg['field.iddistrito']} #{p.iddistrito}" />
                                    <h:outputText value="#{msg['field.provincia']} #{p.provincia.provincia}" />

                                </h:panelGrid>
                            </f:facet>
                        </p:autoComplete>
```

**Segmento Controller**

* En el parámetro adicional colocamos el documento referenciado.

```java
public List<Distrito> completeDistrito(String query) {
            List<Distrito> suggestions = new ArrayList<>();

        try {
          JsfUtil.testMessage("provincia "+fiador.getProvincia().getIdprovincia());
            query = query.trim();
            if (query.length() < 1) {
                return suggestions;
            }

            suggestions = distritoRepository.findRegex("distrito", query, true, "provincia.idprovincia",fiador.getProvincia().getIdprovincia(),new Document("distrito", 1));


        } catch (Exception e) {
            JsfUtil.errorMessage("completeDescripcion() " + e.getLocalizedMessage());
        }
        return suggestions;
    }
```
