1

I want to implement OR filter functionality in cube.js. This link says we can do this by using segments option in cubejs params.

How to use segments and what is its purpose? I tried understanding from the website with their 5 lines of documentation about it but failed to understand how to use it.

Pragya Dalal
  • 68
  • 2
  • 9

1 Answers1

2

Segments are predefined filters.

You can use segments to define complex filtering logic in SQL. For example, users for one particular city can be treated as a segment.

cube(`Users`, {
  // ...

  segments: {
    sfUsers: {
      sql: `${CUBE}.location = 'San Francisco'`
    }
  }
});

Or use segments to implement cross-column OR logic:

cube(`Users`, {
  // ...

  segments: {
    sfUsers: {
      sql: `${CUBE}.location = 'San Francisco' or ${CUBE}.state = 'CA'`
    }
  }
});

As with other cube member definitions segments can be generated:

const userSegments = {
  sfUsers: ['San Francisco', 'CA'],
  nyUsers: ['New York City', 'NY']
}

cube(`Users`, {
  // ...

  segments: {
    ...(Object.keys(userSegments).map(segment => ({
      [segment]: {
        sql: `${CUBE}.location = '${userSegments[segment][0]}' or ${CUBE}.state = '${userSegments[segment][1]}'`
      }
    })).reduce((a, b) => ({ ...a, ...b })))
  }
});

After defining a segment, you can pass it in query object:

{
  measures: ['Users.count'],
  segments: ['Users.sfUsers']
}
Pavel Tiunov
  • 1,163
  • 6
  • 8