Example #1
0
    def values(self, request: request.Request, **kwargs) -> response.Response:
        key = request.GET.get("key")
        value = request.GET.get("value")
        flattened = []
        if key:
            timer = statsd.timer("get_person_property_values_for_key_timer").start()
            try:
                result = get_person_property_values_for_key(key, self.team, value)
                statsd.incr(
                    "get_person_property_values_for_key_success",
                    tags={"key": key, "value": value, "team_id": self.team.id},
                )
            except Exception as e:
                statsd.incr(
                    "get_person_property_values_for_key_error",
                    tags={"error": str(e), "key": key, "value": value, "team_id": self.team.id},
                )
                raise e
            finally:
                timer.stop()

            for (value, count) in result:
                try:
                    # Try loading as json for dicts or arrays
                    flattened.append({"name": convert_property_value(json.loads(value)), "count": count})  # type: ignore
                except json.decoder.JSONDecodeError:
                    flattened.append({"name": convert_property_value(value), "count": count})
        return response.Response(flattened)
Example #2
0
    def values(self, request: request.Request) -> response.Response:
        key = request.GET.get('key')
        params = [key, key]
        if request.GET.get('value'):
            where = " AND properties ->> %s LIKE %s"
            params.append(key)
            params.append('%{}%'.format(request.GET['value']))
        else:
            where = ''

        params.append(request.user.team_set.get().pk)
        # This samples a bunch of events with that property, and then orders them by most popular in that sample
        # This is much quicker than trying to do this over the entire table
        values = Event.objects.raw(
            """
            SELECT
                value, COUNT(1) as id
            FROM ( 
                SELECT
                    ("posthog_event"."properties" -> %s) as "value"
                FROM
                    "posthog_event"
                WHERE
                    ("posthog_event"."properties" -> %s) IS NOT NULL {} AND
                    ("posthog_event"."team_id" = %s)
                LIMIT 10000
            ) as "value"
            GROUP BY value
            ORDER BY id DESC
            LIMIT 50;
        """.format(where), params)

        return response.Response([{
            'name': convert_property_value(value.value)
        } for value in values])
Example #3
0
 def values(self, request: Request) -> Response:
     key = request.GET.get("key")
     team = request.user.team
     result = []
     if key:
         result = get_property_values_for_key(key, team)
     return Response([{"name": convert_property_value(value[0])} for value in result])
Example #4
0
    def values(self, request: Request, **kwargs) -> Response:

        key = request.GET.get("key")
        team = self.team
        result = []
        if key:
            result = get_property_values_for_key(key, team, value=request.GET.get("value"))
        return Response([{"name": convert_property_value(value[0])} for value in result])
Example #5
0
    def values(self, request: Request) -> Response:

        if not endpoint_enabled(CH_EVENT_ENDPOINT, request.user.distinct_id):
            return Response(super().get_values(request))

        key = request.GET.get("key")
        team = request.user.team
        result = []
        if key:
            result = get_property_values_for_key(key, team, value=request.GET.get("value"))
        return Response([{"name": convert_property_value(value[0])} for value in result])
Example #6
0
    def get_values(self, request: request.Request) -> List[Dict[str, Any]]:
        key = request.GET.get("key")
        params: List[Optional[Union[str, int]]] = [key, key]

        if key == "custom_event":
            event_names = (
                Event.objects.filter(team_id=self.team_id)
                .filter(~Q(event__in=["$autocapture", "$pageview", "$identify", "$pageleave", "$screen"]))
                .values("event")
                .distinct()
            )
            return [{"name": value["event"]} for value in event_names]

        if request.GET.get("value"):
            where = " AND properties ->> %s LIKE %s"
            params.append(key)
            params.append("%{}%".format(request.GET["value"]))
        else:
            where = ""

        params.append(self.team_id)
        params.append(relative_date_parse("-7d").strftime("%Y-%m-%d 00:00:00"))
        params.append(timezone.now().strftime("%Y-%m-%d 23:59:59"))

        # This samples a bunch of events with that property, and then orders them by most popular in that sample
        # This is much quicker than trying to do this over the entire table
        values = Event.objects.raw(
            """
            SELECT
                value, COUNT(1) as id
            FROM (
                SELECT
                    ("posthog_event"."properties" -> %s) as "value"
                FROM
                    "posthog_event"
                WHERE
                    ("posthog_event"."properties" -> %s) IS NOT NULL {} AND
                    ("posthog_event"."team_id" = %s) AND
                    ("posthog_event"."timestamp" >= %s) AND
                    ("posthog_event"."timestamp" <= %s)
                LIMIT 10000
            ) as "value"
            GROUP BY value
            ORDER BY id DESC
            LIMIT 50;
        """.format(
                where
            ),
            params,
        )

        flattened = flatten([value.value for value in values])
        return [{"name": convert_property_value(value)} for value in flattened]
Example #7
0
    def values(self, request: request.Request) -> response.Response:
        people = self.get_queryset()
        key = "properties__{}".format(request.GET.get('key'))
        people = people\
            .values(key)\
            .annotate(count=Count('id'))\
            .filter(**{'{}__isnull'.format(key): False})\
            .order_by('-count')

        if request.GET.get('value'):
            people = people.extra(where=["properties ->> %s LIKE %s"], params=[request.GET['key'], '%{}%'.format(request.GET['value'])])

        return response.Response([{'name': convert_property_value(event[key]), 'count': event['count']} for event in people[:50]])
Example #8
0
 def values(self, request: Request, **kwargs) -> Response:
     key = request.GET.get("key")
     team = self.team
     result = []
     flattened = []
     if key:
         result = get_property_values_for_key(key, team, value=request.GET.get("value"))
         for value in result:
             try:
                 # Try loading as json for dicts or arrays
                 flattened.append(json.loads(value[0]))
             except json.decoder.JSONDecodeError:
                 flattened.append(value[0])
     return Response([{"name": convert_property_value(value)} for value in flatten(flattened)])
Example #9
0
 def values(self, request: request.Request, **kwargs) -> response.Response:
     key = request.GET.get("key")
     team = self.team
     flattened = []
     if key == "custom_event":
         events = sync_execute(GET_CUSTOM_EVENTS, {"team_id": team.pk})
         return response.Response([{"name": event[0]} for event in events])
     elif key:
         result = get_property_values_for_key(key, team, value=request.GET.get("value"))
         for value in result:
             try:
                 # Try loading as json for dicts or arrays
                 flattened.append(json.loads(value[0]))
             except json.decoder.JSONDecodeError:
                 flattened.append(value[0])
     return response.Response([{"name": convert_property_value(value)} for value in flatten(flattened)])
Example #10
0
    def values(self, request: request.Request, **kwargs) -> response.Response:
        people = self.get_queryset()
        key = "properties__{}".format(request.GET.get("key"))
        people = (
            people.values(key)
            .annotate(count=Count("id"))
            .filter(**{"{}__isnull".format(key): False})
            .order_by("-count")
        )

        if request.GET.get("value"):
            people = people.extra(
                where=["properties ->> %s LIKE %s"], params=[request.GET["key"], "%{}%".format(request.GET["value"])],
            )

        return response.Response(
            [{"name": convert_property_value(event[key]), "count": event["count"]} for event in people[:50]]
        )
Example #11
0
    def get_values(self, request: request.Request) -> List[Dict[str, Any]]:
        key = request.GET.get("key")
        params = [key, key]
        if request.GET.get("value"):
            where = " AND properties ->> %s LIKE %s"
            params.append(key)
            params.append("%{}%".format(request.GET["value"]))
        else:
            where = ""

        team = request.user.team
        assert team is not None
        params.append(team.pk)
        # This samples a bunch of events with that property, and then orders them by most popular in that sample
        # This is much quicker than trying to do this over the entire table
        values = Event.objects.raw(
            """
            SELECT
                value, COUNT(1) as id
            FROM (
                SELECT
                    ("posthog_event"."properties" -> %s) as "value"
                FROM
                    "posthog_event"
                WHERE
                    ("posthog_event"."properties" -> %s) IS NOT NULL {} AND
                    ("posthog_event"."team_id" = %s)
                LIMIT 10000
            ) as "value"
            GROUP BY value
            ORDER BY id DESC
            LIMIT 50;
        """.format(where),
            params,
        )

        return [{
            "name": convert_property_value(value.value)
        } for value in values]